I hope someone can point out where I am going wrong with this update, I have tried various ways but just can't seem to get it to work, probably a simple mistake but I just can't seem to find it.
function set_live($row_id, $mobile_number)
{
global $conn;
$live = 1;
$sql = "
UPDATE
connections
SET
live = :live,
voice_number = :mobile_number
WHERE
id = :row_id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':mobile_number', $mobile_number, PDO::PARAM_INT);
$stmt->bindParam(':row_id', $row_id, PDO::PARAM_INT);
$stmt->bindParam(':live', $live, PDO::PARAM_INT);
$stmt->execute();
echo "Record edited successfully";
$conn=null;
}
$conn is the PDO connection which works with SELECT's etc
All variables are numbers and all echo OK so are in the function
I can run the query with the actual values in phpmyadmin and it works OK
Just replace this line
$stmt->bindParam(':mobile_number', $mobile_number, PDO::PARAM_INT);
with this
$stmt->bindParam(':mobile_number', $mobile_number, PDO::PARAM_STR);
Because the phone number length is more than integer.
Why not try using an Array? That approach may well do the Trick for you:
<?php
function set_live($row_id, $mobile_number){
global $conn;
$live = 1;
$sql = "UPDATE connections SET live=:live, voice_number=:mobile_number WHERE id=:row_id";
$stmt = $conn->prepare($sql);
$params = array(
"live" =>$live,
"mobile_number" =>$mobile_number,
"row_id" =>$row_id,
);
$stmt->execute($params);
echo "Record edited successfully";
$conn=null;
}
Related
I'm trying to update a number of rows in MySql with a prepared PDO statement. It doesn't emit any error but the rows remains untouched. What am I doing wrong?
I replaced username, password and database name with xxx for the sake of security when posting on Stack Overflow.
<?php
header('Access-Control-Allow-Origin: *');
$jsonp = false;
error_reporting(E_ALL);
ini_set("display_errors", 1);
$db = new PDO('mysql:host=localhost;dbname=xxx;charset=utf8', 'xxx', 'xxx');
$party = ($_POST['party']);
$id = ($_POST['id']); /* String with ids. Ex. "1, 2, 3" */
$state = ($_POST['state']);
$code = ($_POST['fetchCode']);
$stmt = $db->prepare("UPDATE wishes SET state = :state WHERE fetchCode = :code AND partyID = :party AND id IN (:id)");
$stmt->bindParam(':party', $party);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':state', $state);
$stmt->bindParam(':code', $code);
$stmt->execute();
echo json_encode("Done");
?>
In your $_POST['id'] there is space after comma. Please try to avoid spaces before and after comma.
Secondly you can add third parameter PARAM_STR to $stmt->bindParam(':id', $id,PARAM_STR); so that it could be treated as a string while preparing query.
Also add error handler to see the error like :
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($db->errorInfo());
}
One last thing which can help in debugging is you can see what is your final query getting prepared by echo $stmt->queryString
I'm here trying to update my DB rows without deleting/creating new ones all the time. Currently, my DB creates new entries everytime I run this block of code. Instead of spamming my DB, I just want to change some of the values.
<?php
try {
$conn = new PDO("mysql:host=localhost;port=3306;dbname=dbname", Username, password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['mUsername']))
{
$mUsername = urldecode($_POST['mUsername']);
$mEvent = urldecode($_POST['mEvent']);
$mChat = urldecode($_POST['mChat']);
$mlongitude = urldecode($_POST['mlongitude']);
$mlatitude = urldecode($_POST['mlatitude']);
$sqlUPDATE = "UPDATE users
SET lastEvent=:lastEvent, lastChat=:lastChat,
lastLong=:lastLong, lastLatt=:lastLatt
WHERE name=:name";
$stmt = $conn->prepare($sqlUPDATE);
$stmt->bindParam(':lastEvent', $mEvent);
$stmt->bindParam(':lastChat', $mChat);
$stmt->bindParam(':lastLong', $mlongitude);
$stmt->bindParam(':lastLatt', $mlatitude);
$stmt->bindParam(':name', $mUsername);
$stmt->execute();
}
echo "successfully updated";
?>
My assumption is my final line, the $results area. I believe it's just treating this an a new entry instead of an update. How do I go about just replacing values? some values will not change, like the username, and sometimes longitude/latitude won't need to be changed. Would that have to be a separate query, should I split this in to two scripts? Or could I just enter a blank, null value? Or would that end up overwriting the ACTUAL last coordinates, leaving me with null values? Looking for any help or guides or tutorials. Thank you all in advance.
lots of syntax error in your code. It is simple to use bindParam
$sqlUPDATE = "UPDATE users
SET lastEvent=:lastEvent, lastChat=:lastChat,
lastLong=:lastLong, lastLatt=:lastLatt
WHERE name=:name";// you forget to close statement in your code
$stmt = $conn->prepare($sqlUPDATE);
$stmt->bindParam(':lastEvent', $mEvent);
$stmt->bindParam(':lastChat', $mChat);
$stmt->bindParam(':lastLong', $mlongitude);
$stmt->bindParam(':lastLatt', $mlatitude);
$stmt->bindParam(':name', $mUsername);
$stmt->execute();
read http://php.net/manual/en/pdostatement.bindparam.php
When using prepared statements, you should also make a habbit of following the set rules. Use named parameters. Try this:
if(isset($_POST['mUsername']))
{
$mUsername = urldecode($_POST['mUsername']);
$mEvent = urldecode($_POST['mEvent']);
$mChat = urldecode($_POST['mChat']);
$mlongitude = urldecode($_POST['mlongitude']);
$mlatitude = urldecode($_POST['mlatitude']);
$sqlUPDATE = "UPDATE users SET lastEvent= :lastEvent, lastChat= :lastChat, lastLong= :lastLong, lastLatt= :lastLatt WHERE name= :name";
$q = $conn->prepare($sqlUPDATE);
$results = $q->execute(array(':name'=>$mUsername, ':lastEvent'=>$mEvent, ':lastChat'=>$mChat, ':lastLong'=>$mlongitude, ':lastLatt'=>$mlatitude));
}
FYI: this file is my very first touch with PDO.
I have converted a mysqli PHP file info a PDO PHP file, it works fine. File's goal is: if user does not pass any value on keys ($ca_key1 - $ca_key3) just insert data on DB. If keys are passed and do not exist on DB, insert data on DB. If they do exist, echo an error.
I knew PDO could seem redundant, but in this case where I use same parameters up to 3 times on the same file, I ask: is there any way of binding parameter just one time and use it on the 3 executions? For example, ca_key1 could be just binded once and used on the 3 executions?
If you find any error/mistake on the file apart from this, I would appreciate if you mention me. I'd like to adapt good habits on PDO from the begining.
<?php
session_start();
include("../conexionbbdd.php");
if($_SESSION['estado'] == 'activo'){
if (isset($_POST['ca_name'])&&isset($_POST['ca_content'])&&isset($_POST['ca_img'])&&isset($_POST['ca_key1'])&&isset($_POST['ca_key2'])&&isset($_POST['ca_key3'])){
//CHECK IF USER PASSED VALUES ON KEYS
$ca_key1=$_POST['ca_key1'];
$ca_key2=$_POST['ca_key2'];
$ca_key3=$_POST['ca_key3'];
//IF PASSED, CHECK IF VALUES EXIST ON DB
if ($ca_key1!=="" || $ca_key2!=="" || $ca_key3!==""){
$selectKeys= "SELECT ca_key1,ca_key2,ca_key3 FROM ws_campaigns WHERE ca_fk_us_id = :us_id AND ("
. " (ca_key1!='' AND ca_key1 = :ca_key1) OR (ca_key2!='' AND ca_key2 = :ca_key1) OR (ca_key3!='' AND ca_key3 = :ca_key1) "
. "OR (ca_key1!='' AND ca_key1 = :ca_key2) OR (ca_key2!='' AND ca_key2 = :ca_key2) OR (ca_key3!='' AND ca_key3 = :ca_key2)"
. "OR (ca_key1!='' AND ca_key1 = :ca_key3) OR (ca_key2!='' AND ca_key2 = :ca_key3) OR (ca_key3!='' AND ca_key3 = :ca_key3))";
$statementKeys = $pdo->prepare($selectKeys);
$statementKeys->bindParam(':us_id', $_SESSION['id'], PDO::PARAM_INT);
$statementKeys->bindParam(':ca_key1', $_POST['ca_key1'], PDO::PARAM_STR);
$statementKeys->bindParam(':ca_key2', $_POST['ca_key2'], PDO::PARAM_STR);
$statementKeys->bindParam(':ca_key3', $_POST['ca_key3'], PDO::PARAM_STR);
$statementKeys->execute();
$cuenta = $statementKeys->rowCount();
//IF NOT EXIST, INSERT DATA
if ($cuenta === 0){
$insertCampaign = "INSERT INTO ws_campaigns(ca_id,ca_name, ca_content,ca_fk_us_id,ca_img,ca_prefix,ca_key1,ca_key2,ca_key3
)VALUES('',:ca_name,:ca_content,:us_id,:ca_img,'34',:ca_key1,:ca_key2,:ca_key3)";
$statementInsertCampaign = $pdo->prepare($insertCampaign);
$statementInsertCampaign->bindParam(':us_id', $_SESSION['id'], PDO::PARAM_INT);
$statementInsertCampaign->bindParam(':ca_name', $_POST['ca_name'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_content', $_POST['ca_content'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_img', $_POST['ca_img'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key1', $_POST['ca_key1'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key2', $_POST['ca_key2'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key3', $_POST['ca_key3'], PDO::PARAM_STR);
$statementInsertCampaign->execute();
$newId = $pdo->lastInsertId();
echo $newId;
}
else{
echo "No se ha creado la campaña. <br>Alguna de las palabras clave utilizadas ya están presentes en una campaña anterior.";
}
}else{
//IF NO VALUES PASSED, INSERT DATA
$insertCampaign = "INSERT INTO ws_campaigns(ca_id,ca_name, ca_content,ca_fk_us_id,ca_img,ca_prefix,ca_key1,ca_key2,ca_key3
)VALUES('',:ca_name,:ca_content,:us_id,:ca_img,'34',:ca_key1,:ca_key2,:ca_key3)";
$statementInsertCampaign = $pdo->prepare($insertCampaign);
$statementInsertCampaign->bindParam(':us_id', $_SESSION['id'], PDO::PARAM_INT);
$statementInsertCampaign->bindParam(':ca_name', $_POST['ca_name'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_content', $_POST['ca_content'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_img', $_POST['ca_img'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key1', $_POST['ca_key1'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key2', $_POST['ca_key2'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key3', $_POST['ca_key3'], PDO::PARAM_STR);
$statementInsertCampaign->execute();
$newId = $pdo->lastInsertId();
echo $newId;
}
}else{
header('location:../paneles/campana.php?msg=nodata');
}
}else{
header('location:../login.php?msg=nopermission');
}
?>
Actually, you don't have to bind [explicitly] at all.
PDO is a great step further compared to mysqli, and this is one of it benefits: you can create an array of variables, and pass them directly into execute(), instead of binding them one by one - PDO will bind them internally, using PDO::PARAM_STR by default, which is not a problem most of time, save for only one case - LIMIT clause parameres.
It is not only greatly reduces amount of code, but also let you to reuse the same set of variables with different queries.
$data = array(
'us_id' => $_SESSION['id'],
'ca_name' => $_POST['ca_name'],
// and so on
);
$stmt->execute($data);
Of course, array keys have to match placeholders in the query. If your queries have different sets of placeholders, you will need different arrays as well.
I am using two prepared statements in PHP/MySQLi to retrieve data from a mysql database. However, when I run the statements, I get the "Commands out of sync, you can't run the command now" error.
Here is my code:
$stmt = $mysqli->prepare("SELECT id, username, password, firstname, lastname, salt FROM members WHERE email = ? LIMIT 1";
$stmt->bind_param('s', $loweredEmail);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password, $firstname, $lastname, $salt);
$stmt->fetch();
$stmt->free_result();
$stmt->close();
while($mysqli->more_results()){
$mysqli->next_result();
}
$stmt1 = $mysqli->prepare("SELECT privileges FROM delegations WHERE id = ? LIMIT 1");
//This is where the error is generated
$stmt1->bind_param('s', $user_id);
$stmt1->execute();
$stmt1->store_result();
$stmt1->bind_result($privileges);
$stmt1->fetch();
What I've tried:
Moving the prepared statements to two separate objects.
Using the code:
while($mysqli->more_results()){
$mysqli->next_result();
}
//To make sure that no stray result data is left in buffer between the first
//and second statements
Using free_result() and mysqli_stmt->close()
PS: The 'Out of Sync' error comes from the second statement's '$stmt1->error'
In mysqli::query If you use MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result()
When calling multiple stored procedures, you can run into the following error: "Commands out of sync; you can't run this command now".
This can happen even when using the close() function on the result object between calls.
To fix the problem, remember to call the next_result() function on the mysqli object after each stored procedure call. See example below:
<?php
// New Connection
$db = new mysqli('localhost','user','pass','database');
// Check for errors
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
// 1st Query
$result = $db->query("call getUsers()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$user_arr[] = $row;
}
// Free result set
$result->close();
$db->next_result();
}
// 2nd Query
$result = $db->query("call getGroups()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$group_arr[] = $row;
}
// Free result set
$result->close();
$db->next_result();
}
else echo($db->error);
// Close connection
$db->close();
?>
I hope this will help
"Commands out of sync; you can't run this command now"
Details about this error can be found in the mysql docs. Reading those details makes it clear that the result sets of a prepared statement execution need to be fetched completely before executing another prepared statement on the same connection.
Fixing the issue can be accomplished by using the store result call. Here is an example of what I initially was trying to do:
<?php
$db_connection = new mysqli('127.0.0.1', 'user', '', 'test');
$post_stmt = $db_connection->prepare("select id, title from post where id = 1000");
$comment_stmt = $db_connection->prepare("select user_id from comment where post_id = ?");
if ($post_stmt->execute())
{
$post_stmt->bind_result($post_id, $post_title);
if ($post_stmt->fetch())
{
$comments = array();
$comment_stmt->bind_param('i', $post_id);
if ($comment_stmt->execute())
{
$comment_stmt->bind_result($user_id);
while ($comment_stmt->fetch())
{
array_push($comments, array('user_id' => $user_id));
}
}
else
{
printf("Comment statement error: %s\n", $comment_stmt->error);
}
}
}
else
{
printf("Post statement error: %s\n", $post_stmt->error);
}
$post_stmt->close();
$comment_stmt->close();
$db_connection->close();
printf("ID: %d -> %s\n", $post_id, $post_title);
print_r($comments);
?>
The above will result in the following error:
Comment statement error: Commands out of sync; you can't run this command now
PHP Notice: Undefined variable: post_title in error.php on line 41
ID: 9033 ->
Array
(
)
Here is what needs to be done to make it work correctly:
<?php
$db_connection = new mysqli('127.0.0.1', 'user', '', 'test');
$post_stmt = $db_connection->prepare("select id, title from post where id = 1000");
$comment_stmt = $db_connection->prepare("select user_id from comment where post_id = ?");
if ($post_stmt->execute())
{
$post_stmt->store_result();
$post_stmt->bind_result($post_id, $post_title);
if ($post_stmt->fetch())
{
$comments = array();
$comment_stmt->bind_param('i', $post_id);
if ($comment_stmt->execute())
{
$comment_stmt->bind_result($user_id);
while ($comment_stmt->fetch())
{
array_push($comments, array('user_id' => $user_id));
}
}
else
{
printf("Comment statement error: %s\n", $comment_stmt->error);
}
}
$post_stmt->free_result();
}
else
{
printf("Post statement error: %s\n", $post_stmt->error);
}
$post_stmt->close();
$comment_stmt->close();
$db_connection->close();
printf("ID: %d -> %s\n", $post_id, $post_title);
print_r($comments);
?>
A couple things to note about the above example:
The bind and fetch on the statement still works correctly.
Make sure the results are freed when the processing is done.
For those of you who do the right thing and use stored procedures with prepared statements.
For some reason mysqli cannot free the resources when using an output variable as a parameter in the stored proc. To fix this simply return a recordset within the body of the procedure instead of storing the value in an output variable/parameter.
For example, instead of having SET outputVar = LAST_INSERT_ID(); you can have SELECT LAST_INSERT_ID(); Then in PHP I get the returned value like this:
$query= "CALL mysp_Insert_SomeData(?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("is", $input_param_1, $input_param_2);
$stmt->execute() or trigger_error($mysqli->error); // trigger_error here is just for troubleshooting, remove when productionizing the code
$stmt->store_result();
$stmt->bind_result($output_value);
$stmt->fetch();
$stmt->free_result();
$stmt->close();
$mysqli->next_result();
echo $output_value;
Now you are ready to execute a second stored procedure without having the "Commands out of sync, you can't run the command now" error. If you were returning more than one value in the record set you can loop through and fetch all of them like this:
while ($stmt->fetch()) {
echo $output_value;
}
If you are returning more than one record set from the stored proc (you have multiple selects), then make sure to go through all of those record sets by using $stmt->next_result();
I'm sure this will somebody no time at all.
I know that MySqli works on this server as i have tried inserts and they work fine.
I also know that the information I'm trying to obtain is in the database and i can connect to the database without any problems. But I can't for the life of me figure out why this isn't working. I've tried both OO and Procedural but neither of them work. Can someone tell me what it is i'm supposed to be doing? Thanks
$table = 'newcms_broadcasting';
$sql = "SELECT first_info1 FROM $table WHERE region_id = ?";
echo $sql;
//echo $sql;
$region = '1';
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param("s", $region);
mysqli_execute();
mysqli_bind_result($result);
echo 'blah';
// display the results
mysqli_fetch($stmt);
echo "name: $result";
// clean up your mess!
mysqli_close($stmt);
When using procedural style, you should pass $stmt into mysqli_stmt_bind_param, mysqli_stmt_execute, mysqli_bind_result etc
mysqli_stmt_bind_param($stmt, "s", $region);
mysqli_stmt_execute($stmt);
mysqli_bind_result($stmt, $result);
while (mysqli_stmt_fetch($stmt)) {
print_r($result);
}
you forgot to include your compiled statement in binding results:
mysqli_stmt_bind_result($stmt, $result);
also note, that mysqli_fetch is deprecated, have you tried using a classic fetching while loop?
while (mysqli_stmt_fetch($stmt)) {
print_r($result);
}