Stored procedure within function failing because of missing values - php

I can't figure out where my error lies here, but I'm calling this function and sending the 3 required arguments but the procedure is failing at execute.
I added a dump and die statement and it prints all 4 parameters being used in the procedure. One thing I'm concerned about is making sure all 4 things are being properly sent in as strings, as they should all be strings in the procedure.
Maybe it's something else because when I add the 4 param values manually into my IDE they successfully enter into the database. Is there an issue with how I'm sending these values?
function createUser($out2,$email,$access){
$type = 'web';
$userStmt = \DB::connection('odbc')->getPdo()->prepare("call schema.insertUser(?,?,?,?)");
$userStmt->bindParam(1, $out2, PDO::PARAM_STR,20);
$userStmt->bindParam(2, $email, PDO::PARAM_STR,140);
$userStmt->bindParam(3, $access, PDO::PARAM_STR, 2500);
$userStmt->bindParam(4, $type, PDO::PARAM_STR, 20);
dd("Out" . $out2 . "Email" . $email . "Access" . $access . "Type" . $type);
$userStmt->execute();
}
Dumping $userStmt
PDOStatement {#845 ▼
+queryString: "call schema.insertuser(?,?,?,?)"
errorInfo: array:4 [▼
0 => ""
1 => 0
2 => " ((null)[0] at (null):0)"
3 => ""
]
}

Related

PHP Error Exception : Only variables should be passed by reference in C:\xampp\htdocs\library-api\master.php on line 259 [duplicate]

This question already has answers here:
PDO pass by reference notice?
(4 answers)
Closed 2 years ago.
I want to display data book but the problem is i got this error
Notice: Only variables should be passed by reference in C:\xampp\htdocs\library-api\master.php on line <i>259</i></th></tr>
and here is my master.php
public function GetReportBook($id_book,$TanggalStart, $TanggalEnd)
{
$sqlsrvquery = "
EXEC [dbo].[GetReportBook]
#id_book = ?,
#TanggalStart = ?,
#TanggalEnd = ?";
$stmt = $this->conn->prepare($sqlsrvquery);
$stmt->bindParam(1, $id_book, PDO::PARAM_STR);
$stmt->bindParam(2, date('Ymd', strtotime($TanggalStart)), PDO::PARAM_STR);
$stmt->bindParam(3, date('Ymd', strtotime($TanggalEnd)), PDO::PARAM_STR);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$report_arr = array(
"status" => true,
"id_book" => $row['id_book'],
"book_name" => $row['book_name'],
//etc
);
} else {
$report_arr = array(
"status" => false,
"message" => "Invalid Get Report Book!",
);
}
print_r(json_encode($report_arr));
}
any solution of this? because i think the error came because of date time
You're passing an expression instead of a variable in the 2nd and 3rd calls to bindParam. As the notice says, only variables should be used when passing by reference. And the bindParam documentation makes clear that the second argument to that function is passed by reference.
So, try it like this:
$startStr = date('Ymd', strtotime($TanggalStart));
$endStr = date('Ymd', strtotime($TanggalEnd));
$stmt->bindParam(2, $startStr, PDO::PARAM_STR);
$stmt->bindParam(3, $endStr, PDO::PARAM_STR);
(N.B. This isn't specific to dates and times, as you mentioned - using any expression would cause the same result.)

PHP MYSQL runs the query twice

When i run the following script. The row is inserted twice ( the query runs twice ) .
require_once $_SERVER['DOCUMENT_ROOT'].'/functions/sanitize.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/main/config.php';
$response = textsanitize($_POST['r']);
$ticket = idssanitize($_POST['t']);
$stmt = $condb->prepare("INSERT INTO ticket_reponses (ticket_id,user_id,time,response) VALUES (:ticket_id,:user_id,:time,:response)");
$stmt->execute(
array(
"ticket_id" => $ticket,
"user_id" => $_SESSION['user_id'],
"time" => time(),
"response" => $response
)
);
if($stmt->execute()){
echo "SUCCESS";
}
When i remove if($stmt->execute()){echo "SUCCESSS";}. It runs in the right way. The row inserted once.
Why does if($stmt->execute()) execute the query again ? I thought that if($stmt->execute()) only returns TRUE || FALSE. I want to ensure that the query was executed successfully.
One of the good uses of prepared statements in any language is that you can prepare it once and then execute it as many times as needed.
So in your case you execute() the statement twice, but it's possible that you could insert a whole bunch of data with the same prepared statement in a loop. Each time you call execute() you can just pass a new set of values to run the prepared statement. In your case it is an INSERT, so this is run twice.
In your case you probably just need...
$stmt = $condb->prepare("INSERT INTO ticket_reponses (ticket_id,user_id,time,response) VALUES (:ticket_id,:user_id,:time,:response)");
if($stmt->execute(array(
"ticket_id" => $ticket,
"user_id" => $_SESSION['user_id'],
"time" => time(),
"response" => $response))) {
echo "SUCCESS";
}
It is because it is calling the $stmt->execute() function twice. Once before the if statement and once as the condition in the if statement.
So, you need to remove one instance of it.
I believe that you need to check if the statement has executed correctly (hence the if). So, the code can be like...
require_once $_SERVER['DOCUMENT_ROOT'].'/functions/sanitize.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/main/config.php';
$response = textsanitize($_POST['r']);
$ticket = idssanitize($_POST['t']);
$stmt = $condb->prepare("INSERT INTO ticket_reponses (ticket_id,user_id,time,response) VALUES (:ticket_id,:user_id,:time,:response)");
$values = array(
"ticket_id" => $ticket,
"user_id" => $_SESSION['user_id'],
"time" => time(),
"response" => $response
);
if($stmt->execute($values)){
echo "SUCCESS";
}
You are executing $stmt->execute() twice, so it's simply inserting two rows. no rocket science here.
if you want to check if the query ran successfully or not do it in the first statement itself.
require_once $_SERVER['DOCUMENT_ROOT'].'/functions/sanitize.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/main/config.php';
$response = textsanitize($_POST['r']);
$ticket = idssanitize($_POST['t']);
$stmt = $condb->prepare("INSERT INTO ticket_reponses (ticket_id,user_id,time,response) VALUES (:ticket_id,:user_id,:time,:response)");
$isSuccessful = $stmt->execute(
array(
"ticket_id" => $ticket,
"user_id" => $_SESSION['user_id'],
"time" => time(),
"response" => $response
)
);
if($isSuccessful){
echo "SUCCESS";
}

PDO Named parameters inside JSON

I have data that should be escaped inside a JSON formatted string, so I'm using PDO's named parameters and PDO::Prepare to bind them.
Because JSON with it's apostrophes causes errors in the MySQL query, i have to use single quotes around it - although this causes the PDO::Prepare to ignore the named parameters inside the JSON, so it fails with SQLSTATE[HY093]: Invalid parameter number: parameter was not defined.
Any ideas how to work around this?
function send($_data) {
global $_SESSION;
global $dbApi;
#These are temporary debug variables:
$_SESSION['room_id'] = 1;
$id = 124;
$json = '"' . $id . '": {"user_id": ":email","data": ":data"}';
$query = "UPDATE `room_index` " .
"SET `data` = JSON_ARRAY_INSERT(`data`, '$[0]', '" . $json . "') " .
"WHERE `id` = :room_id";
$dbApi->query($query, array(':email' => $_SESSION['email'],
':data' => $_data,
':room_id' => $_SESSION['room_id']));
}
To explain the code a bit, :email ($_SESSION['email']) doesn't have to be a parameter, but it's cleaner this way. The main issue is :data ($_data) - that is user input straight from a textarea via JS.
$dbApi is a class with a proper query function, that looks like this:
function query($_query, $_params = array()) {
global $_DB; # <- Database connection object
$query = $_DB->prepare($_query);
if (! $query)
echo $_DB->errorInfo();
try {
$query->execute($_params);
} catch (PDOException $e) {
die( $e->getMessage() );
}
return $query;
}
There are 2 issues with the code.
1. JSON_INSERT is more appropriate.
As I'm inserting a named object into another object (the top level document), the JSON_INSERT offers such a syntax straight away
2. Using JSON_OBJECT instead of manually writing the JSON syntax
As my main issue was, that PDO doesn't replace single, or double quoted parameters, the solution was using JSON_OBJECT, which doesn't require double quotes as they are automatically generated later (my assumption) - but after PDO replaces the variables and also places single quotes around them.
New, tested code outputting valid JSON:
#Temporary, to avoid other unrelated issues
$_SESSION['room_id'] = 1;
$_SESSION['email'] = 'email#email.com';
$id = 123;
$json = 'JSON_OBJECT("user_id", :email, "data", :data)';
$query = "UPDATE `room_index` " .
"SET `data` = JSON_INSERT(`data`, :id, $json) " .
"WHERE `id` = :room_id";
$dbApi->query($query, [':id' => "$." . $id,
':email' => $_SESSION['email'],
':data' => $_data,
':room_id' => $_SESSION['room_id']]);

return array of results from select query php

I'm trying to implement search suggestions for an app and need to search a database table that contains a list of users. I need the script to return an array of with the details of all the users that fit the criteria (i.e if the user searches 'Jo' it'll return users named 'John' 'Joe' etc.). I've had a go at doing this using parts of some of my other scripts but I can't get the mysqli_fetch_array method to work properly.
I'm using an onTextChangedListener to query the script every time the user types something, I believe this is the right way to go about doing it. I'll post my code below, if there's any more info needed just let me know.
$con = mysqli_connect(database details);
$name = $_POST["name"];
$statement = mysqli_prepare($con, "SELECT user_id, name, email FROM users WHERE name = ?");
mysqli_stmt_bind_param($statement, "s", $name);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $user_id, $name, $email);
$response = mysqli_fetch_array($statement, MYSQLI_ASSOC);
echo json_encode($response);
mysqli_close($con);
Within android studio I'm getting the error: mysqli_fetch_array() expects parameter 1 to be mysqli_result.
Try changint the mysqli_fetch array for the following loop:
while (mysqli_stmt_fetch($statement)) {
$response[] = [
"user_id" => $user_id,
"name" => $name,
"email" => $email,
]; //assign each data to response array
}

i am getting error while inserting data into mysql using php(pdo)

<?php
$stmt = $db->prepare("INSERT INTO slider(ZSLIDE_SLIDER_NO, ZSLIDE_TITLE, ZSLIDE_IMG, ZSLIDE_IMG_ALT, ZSLIDE_LINK, ZSLIDE_LINK_TARGET,ZSLIDE_COUNTRY_ID, ZSLIDE_STATUS) VALUES(:ZSLIDE_SLIDER_NO, :ZSLIDE_TITLE, :ZSLIDE_IMG, :ZSLIDE_IMG_ALT, :ZSLIDE_LINK, :ZSLIDE_LINK_TARGET,:ZSLIDE_COUNTRY_ID :ZSLIDE_STATUS)");
$is_success = $stmt->execute(array(":ZSLIDE_SLIDER_NO" => $slider_no, ":ZSLIDE_TITLE" => $title, ":ZSLIDE_IMG" => $thumbimg_filename, ":ZSLIDE_IMG_ALT" => $alt, ":ZSLIDE_LINK" => $link, ":ZSLIDE_LINK_TARGET" => $link_target, ":ZSLIDE_COUNTRY_ID"=>$country_id, ":ZSLIDE_STATUS" => $activate_status));
// print_r($is_success);exit;
if($is_success)
{
echo "<script>alert('Added Successfully.');</script>";
}
else
{
echo "<script>alert('Failed to add.');</script>";
}
Please correctly bind values to your parameters in the query.
Like this :
$stmt->bindParam(':ZSLIDE_SLIDER_NO', $slider_no, PDO::PARAM_INT);
You were trying to bind the parameters while executing the query. This is not possible, so you have to bind the parameters before executing the query.
Also, As Alon Eitan correctly pointed out, you forgot to include a comma between your last two placeholders in your statement :ZSLIDE_COUNTRY_ID :ZSLIDE_STATUS
You missed comma here
:ZSLIDE_COUNTRY_ID :ZSLIDE_STATUS
correct:
:ZSLIDE_COUNTRY_ID,:ZSLIDE_STATUS
Possible errors:
check correct columns in DB for table slider
Check last error of SQL:
else {
echo "< script>alert('Failed to add: " . $db->errorInfor() . ");</ script>";
}
problem
In binding, you have missin ,:
:ZSLIDE_COUNTRY_ID :ZSLIDE_STATUS

Categories