I have a service file where I'm running a stored procedure:
function createCampaign($campaignName, $groupNumber){
$stmt = \DB::connection('odbc')->getPdo()->prepare('CALL SCHEMA.INSERT_CAMPAIGN(?,?,?)');
$stmt->bindValue(1,$campaignName, PDO::PARAM_STR);
$stmt->bindValue(2,$groupNumber, $groupNumber==0 ? PDO::PARAM_NULL : PDO::PARAM_INT);
$stmt->bindParam(3,$out2, PDO::PARAM_INT);
$stmt->execute();
return $out2;
}
When I run this stored procedure, the third parameter is giving back OUT_CAMPAIGN_ID and the expected ID, so this works. I'm returning that output variable with $out2
My controller, which calls the previous function and also expects the return back:
public function createCampaign(Request $request)
{
$campaignName = $request->campaignName;
$groupNumber = $request->groupNumber;
$campaignService = new CampaignService();
$createCampaign = $campaignService->createCampaign($campaignName, (int) $groupNumber);
return Response::json(["OUT_CAMPAIGN_ID" => $createCampaign]);
}
However, when I console log data.OUT_CAMPAIGN_ID in my blade, or even console log data it just gives me OUT_CAMPAIGN_ID:null
Am I doing something wrong in the way I expect it back in the controller?
Stored procedure:
BEGIN
INSERT INTO SCHEMA.TABLE(NAME,NUMBER)
VALUES (IN_NAME, IN_NUMBER);
SET OUT_ID = IDENTITY_VAL_LOCAL();
END;
It sounds like your stored procedure returns a value? I think what you need to do is more like:
$stmt = \DB::connection('odbc')->getPdo()->prepare('CALL SCHEMA.INSERT_CAMPAIGN(?,?,?)');
$stmt->bindValue(1,$campaignName, PDO::PARAM_STR);
$stmt->bindValue(2,$groupNumber, $groupNumber==0 ? PDO::PARAM_NULL : PDO::PARAM_INT);
$stmt->bindParam(3, $out2, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$stmt->execute();
Related
Goal: I am trying to populate a dropdown from a database table column... I need to pass a variable from the front-end to the PHP indicating which table to ping from, as it may change depending on user selection beforehand...
This is where I'm trying to pass my which variable in to use as
this indicator — but I am having a hard time, because I am trying to
do so within a $.get request? If I could get $which = $_GET['id']; to report/gather what I have in my jQuery with let which = $(frm).attr("id"); I should be good to go.
How else could I do this, I don't think I could nor think it would be
any good practice to try and wrap a post around my get or vica
versa? Or chain a post then a get - I just need the PHP to access
my jQuery which variable so it knows which table to query.
Below is my most recent attempt: jquery
$('#agent').click(function(){
let which = $(frm).attr("id");
console.log(which);
$.get('dlteopt', 'id='+which, function (response) { // attempt at id
console.log(response);
$.each(response,function(i,obj){
let dd_data="<option value="+obj+">"+obj+"</option>";
$(dd_data).appendTo('#agent');
console.log(obj);
});
});
});
And the PHP side:
$app->get('/dlteopt', function ($request, $response, $args) {
$which = $_GET['id'];
var_dump($which);
if ($which) {
var_dump($which);
$db = $this->db;
$repo = new coolDBclass($db);
$selectIt = $repo->byCol($which);
}
});
here is function byCol btw: (all should be fine if I can just pass the correct table variable)
public function byCol($which) {
var_dump($which);
if ($which == 'table_1'){
$sql = "SELECT table_1 FROM tab.cool";
} else if ($which == 'table_2'){
$sql = "SELECT table_2 FROM tab.awesome";
} else if ($which == 'table_3'){
$sql = "SELECT table_3 FROM tab.rad";
}
// ............/
the relevant markup:
<select name='agent' id='agent'><option>Placeholder</option></select>
If you're trying to use the second parameter of the $.get method to pass the data, it needs to be an object.
See the examples in the docs.
.get('dlteopt', {id: which }, function (response) {
I created a custom table in wordpress called custom_users and I want to access the records via the API
functions.php
function get_wp_custom_users()
{
global $wpdb;
$custom_users = $wpdb->get_results("SELECT * FROM wp_custom_users");
foreach ($custom_users as $custom_user)
{
echo $custom_user->first_name.' '.$custom_user->last_name;
}
}
add_action('rest_api_init', function()
{
register_rest_route( 'wpcustomusers/v1', '/users/', array(
'methods' => 'GET',
'callback' => 'get_wp_custom_users'
));
});
The API can be accessed via url http://localhost/mywebsite/wp-json/wpcustomusers/v1/users
Do you know how can I return the results inside the for loop as JSON from the API request?
I hope to see all the fields returned.. Thanks for the help.
There is no need of foreach loop, make changes as below.
function get_wp_custom_users(){
global $wpdb;
$custom_users = $wpdb->get_results("SELECT * FROM wp_custom_users");
//change as below.
echo json_encode($custom_users);
}
var_dump $custom_users to make sure $custom_users is not empty. Skip for loop. Replace return with echo.
echo json_encode($custom_users);
In my app the form fields are validated on the client side with javascript (EXTJS).
Although I'not experienced in PHP OOP, I also want to validate them server side with PHP OOP way.
For this - after studying the various possibilities of validation - I am using the following code:
I'm following this example: https://www.youtube.com/watch?v=MlJJyva75t8#t=38.9063742
class Validator
<?php
class Validator {
private $fields = array();
private $field_errors = array();
private $form_is_valid = true;
private $allErrors = array(); //added » edited
public function addField($field_name){
$this->fields[] = $field_name;
$this->field_errors[$field_name] = array();
}
public function addValidationRule($field_name, $field_rule, $value){
$rule_name = $field_rule[0];
switch($rule_name){
case 'empty':
if(strlen($value) == 0){
$this->addValidationError($field_name, ucwords($field_name). " error msg empty");
}
break;
case 'min_lenght':
if(strlen($value) < $field_rule[1]){
$this->addValidationError($field_name, ucwords($field_name). " error msg min_lenght");
}
break;
}
}
private function addValidationError($field_name, $error_message){
$this->form_is_valid = false;
$this->field_errors[$field_name][] = $error_message;
}
public function formValid(){
return $this->form_is_valid;
}
public function outValidationError($field_name){
if(isset($this->field_errors[$field_name])){
foreach($this->field_errors[$field_name] as $field_error){
//$allErrors[] = $field_error;
$this->allErrors[] = $field_error;//added » edited
}
}
}
public function outAllValidationError(){
foreach($this->fields as $field){
$this->outValidationError($field);
}
return $this->allErrors; //added » edited » works ok
}
}
?>
Query with prepared statements
<?php
require('conect.php');
$action = $_REQUEST['action'];
switch($action){
case "create":{
$records = $_POST['records'];
$data = json_decode(stripslashes($records));
$cars = $data->{'cars'};
if ($_SERVER["REQUEST_METHOD"] == "POST") {
require_once('validator.php');
$validator = new Validator();
$validator->addField('cars');
$validator->addValidationRule('cars', array('min_lenght', 4), $cars);
$validator->addValidationRule('cars', array('empty'), $cars);
if($validator->formValid()){
$sqlQuery = "INSERT INTO the_cars (cars)
VALUES (?)";
if($statement = $con->prepare($sqlQuery)){
$statement->bind_param("s", $cars);
$statement->execute();
$success= true;
}else{
$erro = $con->error;
$success = false;
}
}else{
$allErrors = $validator->outAllValidationError();
$success = false;
}
echo json_encode(array(
"success" => $sucess,
'errors'=> $erro,
'errorsValidation'=> $allErrors
));
$statement->close();
$conexao->close();
break;
}
?>
y problem is to export the array of validation errors to the client side with json encode.
If in the outValidacionError() function I uncomment print_r ($ allErrors) and make a form submit with the cars field empty it prints the error on console.
However, I am not able to send these errors to the client side. What is missing?
I appreciate suggestions for improving the code or other solution.
EDITED:
As my json_decode is done for objects and not for an associative array, I have changed the code to make it compatible with the decode that was made, adding $value to addValidationRule()
EDITED
code edited with correct solution
If you use functions to encapsulate behaviour, you should not try to use global variables to store their output. Their side-effects should be minimal and they should only manipulate their own object's properties, if required.
Your $allErrors variable is declared nowhere, especially not as a global variable. So when you fill it inside the function, you get a locally scoped variable that will be thrown away once the function finishes.
You may want to return them from your function
return $allErrors;
and then get the values from the function call:
$allErrors = $validator->outAllValidationError()
i have 2 tables user and tn_user, table user is a table containing information to log in, i made it by tutorial from https://laravel.com/ so basically it was automatically created, while tn_user is a table that i make by myself
USER TABLE
in case u can't see the atribut are id, name, email, password that the important things, email and password in this table is used to logging in
TN_USER TABLE
the atribut are cn_id, cv_name, cv_email, cn_phone, cv_position, cv_address, cv_country, cv_username, cv_password, cv_privileges, those are the important thing
based on the form below i want to insert username and password into table user and the rest into table tn_user and how do i do that? im pretty new to laravel so not really quite understand how, usually i use CI
UserController.php
this is where the code i use to insert data
i use json response to parse the data and not quite sure how to insert data into 2 tables little help here
public function createOrEdit(){
//get current user
$currentUserId = Auth::user()->id;
$isUpdate = false;
$id = Input::get('id');
$user = new UserCompany;
if($id != ""){
$user = UserCompany::where('cn_id', '=', $id)->firstOrFail();
$user->cv_updated_by = $currentUserId;
$user->cv_updated_at = Carbon::now();
$isUpdate = true;
}else{
$user->cv_created_by = $currentUserId;
$user->cv_created_at = Carbon::now();
}
$user->cv_name = Input::get('name');
$user->cv_position = Input::get('position');
$user->cv_email = Input::get('email');
$user->cn_phone = Input::get('phone');
$user->cv_address = Input::get('address');
$user->cv_username = Input::get('username');
$user->cv_password = Input::get('password');
$user->cv_country = Input::get('country');
if($isUpdate){
UserCompany::where('cn_id','=',$id)->update(['cv_updated_by' => $user->cv_updated_by,
'cv_updated_at' => $user->cv_updated_at,
'cv_name' => $user->cv_name,
'cv_position' => $user->cv_position,
'cv_email' => $user->cv_email,
'cn_phone' => $user->cn_phone,
'cv_country' => $user->cv_country,
'cv_username' => $user->cv_username,
'cv_password' => $user->cv_password,
'cv_address' => $user->cv_address]);
}else{
$user->save();
}
$returnedData = UserCompany::all();
$response = array(
'content' => $returnedData,
'status' => 'success',
);
return Response::json($response);
}
UserCompany.php is my model but since im new im not really understand how to use relationship yet
<?php namespace Activity;
use Illuminate\Database\Eloquent\Model;
class UserCompany extends Model {
protected $table = 'tn_user';
public $timestamps = false;
protected $fillable = [
];
/*public function usercompany(){
return $this->belongsTo('Activity\user');
}*/
}
You should know that in the UserCompany class, by setting the fillable, It means you are setting table column which you want to alter, in this case tn_user table. So this means, by setting
protected $fillable = [];
It means, that you are making no table columns should undergo modification when you are using commands like;
$user_details->cv_name = Input::get('cv_name');
Okay, so the first thing that you should know is that when creating two tables i.e users and tn_users you should have a column which carries a value which relate the two tables, I suggest that you are to user id from the users table:
I have noticed that you have used cn_id to be a linker, but it is best if every table has its own incrementing id column and also in this case, its own link_id column
Let's say you are starting over:
Open the command prompt or Terminal and go to you laravel project folder directory and type: -$ php artisan make:model User -m and again -$ php artisan make:model UserDetail -m
What this will do is, create User and UserDetail, and adding the -m means its creating the migrations for the models associated which is create_users_table and create_user_details_table
From the create_users_table simply create the desired table columns as shown below:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table){
$table->increments('id');
$table->integer('auth');
$table->string('username')->unique();
$table->string('email');
$table->string('password');
$table->boolean('online');
$table->string('lang', 2);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::drop('users');
}
}
Now for the create_tn_users_table its kinda important, you should set which links with the users account so that suppose you delete the users, his credentials are also removed, but you can make it do otherwise if you want.
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTnUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tn_users', function (Blueprint $table) {
$table->increments('id');
$table->string('full_name');
$table->string('username')->unique();
$table->integer('link_user_id')
->references('id')->on('users'); // Relationship btn table tn_users and users
$table->string('phone');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('tn_users');
}
}
Now go the command prompt or terminal and type -$ php artisan migrate to have the tables created.
Again on the command prompt or terminal type -$ php artisan make:controller UserController --resource and have the controller made together with its resources.
On the create() function inside the UserController, add the Request in as a parameter.
The functions is to be reached upon the submission of the form that you have created
namespace App\Http\Controllers;
use App\User;
use App\TnUser;
use ...
class UserController extends Controller{
public function create(Request $request){
$tn_user = new TnUser();
$user = new User();
$user->username = $request['username'];
$user->password = bcrypt($request['username']);
...
$user->save();
$tn_user->full_name = ucword(strtolower($request['full_name'));
$tn_user->link_user_id = $user->id; // uses the previously save id
$tn_user->phone = trim($request['phone']);
$th_user->save();
}
}
I hope I have answered you questions. Here are some helpful links to learn.
https://laravel.com/docs/5.1/migrations#creating-columns
https://laravel.com/docs/5.1/requests
You Create 2 objects
$user = new User()
$user->username = INPUT::get('username');
$user->password = $password // Hashed
$user->save();
$user_detail = new UserCompany() // Your detail table modal.
$user_detail->cv_name = Input::get('cv_name');
//etc
$user_detail->save()
I am trying to retrieve the data stored in a mySQL table with a PHP script. I want this data to be returned as an array because I then loop through it in my AngularJS app and conduct various transformations etc. I am getting the data out just fine, but it is returned as just one item in an array i.e. each row is not returned as a separate item of the array. My code as it stands is:
PHP Get Request
<?php
require 'config.php';
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * FROM user_details';
$stmt = $pdo->prepare( $sql );
$stmt->execute();
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
$json = json_encode( $result );
echo $json;
Database::disconnect();
?>
Angular Controller
$scope.userprofiles = [];
$http.get('php/getUserDetails.php')
.success(function(data) {
$scope.userprofiles = data;
});
I also run some tests to see what the issue is. Specifically, I see if the variable is an array with:
$scope.varcheck = $scope.userprofiles.constructor === Array;
This returns true. And then I check the length of the array with:
$scope.numRecords = $scope.userprofiles.length;
This returns 0.
If anyone had any thoughts it would be a great help.
I also have an issue that if a "/" or a "'" is stored in the database it throws the get request. I assume that it is exiting early. If anyone knew about this it would be great too!
Thanks,
Jack
$http methods return a promise, which can't be iterated, so you have to attach the results to the scope variable through the callbacks:
$scope.userprofiles = [];
$http.get('php/getUserDetails.php')
.then(function(response) {
$scope.userprofiles = response.data;
});
Hope it may help you :-)