Update multiples columns using PDO - php

How do i add multiples columns in pdo for update? this is what I am trying to do but I need to update multiple $_POSTS['VARS];
$consulta = $conexao_pdo->prepare('UPDATE user SET nome = ? WHERE id = ?');
$consulta->bindParam(1, $variavel_com_nome);
$consulta->bindParam(2, $id);
if ($consulta->execute()) {
echo 'UPDATED';
}

What is it that is not working in your code? If you need to update multiple columns, you just need to include them in your update statement: update table1 set col1 = ?, col2 = ?, col3 = ? where id = ?; then assign parameter values for each one.

This is how I solved it
$sql = "UPDATE user SET name = :name,
surname = :surname
WHERE username = :username";
//db column and value
$stmt = $conexao_pdo->prepare($sql);
//where clause
$stmt->bindParam(':username', $username);
//add vars to db
$stmt->bindParam(':name', $var);
$stmt->bindParam(':surname', $var);
$stmt->execute();

Related

How to update two table with prepared statements?

I've run into some trouble trying to figure out how to update two mysql tables using prepared statements. The first table is updated with the new data but not the second. Can anyone tell me what I've got wrong? Thanks.
/Update Databases
$stmt = $db_conx->prepare('UPDATE tbl_users SET user_name=?, role=?, user_email= ?, company = ?, bio = ?, website = ? WHERE user_id=?');
$stmt->bind_param('sssssss',$user_name,$role,$user_email,$company,$bio,$website,$phone_no, $user_id);
$stmt->execute();
//Update second table
$stmt = $db_conx->prepare('UPDATE useroptions SET user_name=? WHERE user_id=?');
$stmt->bind_param('ss',$user_name,$user_id);
$stmt->execute();
//
if($stmt){
echo
'success";
}
else{ echo "An error occurred!"; }
You have a wrong number of argument in first query 7 ? 7 s but 8 $var ($phone_no )
//Update Databases
$stmt = $db_conx->prepare('UPDATE tbl_users SET user_name=?, role=?, user_email= ?, company = ?, bio = ?, website = ? WHERE user_id=?');
$stmt->bind_param('sssssss',$user_name,$role,$user_email,$company,$bio,$website,$phone_no, $user_id);
^^^^^^
$stmt->execute();
//Update second table
$stmt = $db_conx->prepare('UPDATE useroptions SET user_name=? WHERE user_id=?');
$stmt->bind_param('ss',$user_name,$user_id);
$stmt->execute();
//

How to write PHP file to update database without ID or name?

I am new to writing php file and are currently trying to create a database which stores heart rate measured together with the timestamp.
However I got confused how should I write for the update php file. Anyone knows how to write it given my situation where my
$statement = mysqli_prepare($con, "UPDATE `User` SET timestamp = ?, heartrate = ?, WHERE ***what to include here*** = ?"); // I am not sure what to include here.
Code of my store data in database:
$con = mysqli_connect("server27.000webhost.com" , "a6244607_history" , "123" , "a6244607_history");
$timestamp = $_POST["timestamp"];
$heartrate = $_POST["heartrate"];
$statement = mysqli_prepare($con, "INSERT INTO `User` (timestamp, heartrate) VALUES (?, ?) ");
mysqli_stmt_bind_param($statement, "ss", $timestamp, $heartrate);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);?>
Code to fetch data from database:
$con = mysqli_connect("server27.000webhost.com" , "a6244607_history" , "123" , "a6244607_history");
$timestamp = $_POST["timestamp"];
$heartrate = $_POST["heartrate"];
$statement = mysqli_prepare($con, "SELECT * FROM `User` WHERE timestamp = ? AND heartrate = ?");
mysqli_stmt_bind_param($statement, "ss", $timestamp, $heartrate);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $timestamp, $heartrate);
$user = array();
while(mysqli_stmt_fetch($statement))
{
$user[timestamp] = $timestamp;
$user[heartrate] = $heartrate;
}
echo json_encode($user);
mysqli_stmt_close($statement);
mysqli_close($con);?>
Code to update database:
$con = mysqli_connect("server27.000webhost.com" , "a6244607_history" , "123" , "a6244607_history");
$timestamp = $_POST["timestamp"];
$heartrate = $_POST["heartrate"];
$statement = mysqli_prepare($con, "UPDATE `User` SET timestamp = ?, heartrate = ?, WHERE username = ?");
mysqli_stmt_bind_param($statement, "ss", $timestamp, $heartrate);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
On a side note, is my timestamp written correctly? Sorry for asking so much questions at once...
Hope to get some help soon, thank you.
1) You should not include credentials to your MySQL server on the post
2) Considering you only have 3 tables (user_id, heartrate, timestamp) and in this Prepared Statement:
UPDATE `User` SET timestamp = ?, heartrate = ?, WHERE ***what to include here*** = ?
You use timestamp and heart rate, so for what to include here should be user_id.
If you want to insert a brand new heart rate, use INSERT instead of SET.
Also, your statement should look like:
UPDATE `User` SET `timestamp` = ?, `heartrate` = ?, WHERE `user_id` = ?
Use the grave (`) around table names.

I can't input the data into my table using prepared statements

I can't input the data into my MySQL table using this script:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
session_start();
include '../scripts/test_ses.php';
include 'connection.php';
$date = date("Y-m-d");
/* Set our params */
$id = $_POST['id'];
$status = $_POST['status'];
$active = 1;
$sql = "INSERT INTO TBL_Holiday (Status, Active, DateOfChange) VALUES (?, ?, ?) WHERE idRequest =$id";
$stmt = $conn->prepare($sql);
/* Bind our params */
$stmt->bind_param('iisi', $status, $active, $date, $id);
/* Execute the prepared Statement */
$stmt->execute();
/* Close the statement */
$stmt->close();
?>
The data of the variables $id, $status is set by a form is there any way to display the php error of the script by alerting it on the form page over ajax ?
remove the $id and WHERE they are used for update or delete a row, in your case insert use below query
$sql = "INSERT INTO TBL_Holiday
(Status, Active, DateOfChange) VALUES
(?, ?, ?)";
or if you wanted to update you need to use below query
$sql = "UPDATE TBL_Holiday SET
Status= ?,
Active= ?,
DateOfChange= ?
WHERE idRequest = ?";
/* Bind our params */
$stmt->bind_param('iisi', $status, $active, $date, $id);
by having its id.. make the update operation..
$sql = "UPDATE TBL_Holiday SET Status='$status', Active='$active', DateOfChange='$date' WHERE idRequest =$id";
otherwise.. make insert by ..
$sql = "INSERT INTO TBL_Holiday (Status, Active, DateOfChange) VALUES ('$status', '$active', '$date')";
Instead of using insert you need to use Update query if you need to use condition while. So your condition will be something like this,
$sql = "UPDATE TBL_Holiday SET Status= ?,Active= ?,DateOfChange=? WHERE idRequest =$id";
You're mixing an INSERT statement with an UPDATE statement
An insert statement is on the form:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3,...);
Where you're creating a new record which is not associated with any other existing rows using a where clause, i.e. you're suppose to skip that part.
Meanwhile an update statement is on the form:
UPDATE table_name
SET column1=value1, column2=value2,...
WHERE some_column=some_value;
Where you do indeed wish to associate your update with some specific row by using a where clause, to indicate which row is to be updated.
Not my favorite sources but you can take a look at insert and update.
This is the working code:
<?php
/* Set our params */
$date = date("Y-m-d");
$id = $_POST['id'];
$status = $_POST['status'];
$active = 1;
/*Create executed SQL*/
$sql = "UPDATE TBL_Holiday SET
Status= ?,
Active =?,
DateOfChange =?
WHERE idRequest = ?";
/*Prepare SQL connection*/
$stmt = $conn->prepare($sql);
/* Bind our params */
$stmt->bind_param('iisi', $status, $active, $date, $id);
/* Execute the prepared Statement */
$stmt->execute();
/* Close the statement */
$stmt->close();
?>

Insert stmt with a Select and additional Params

Is it possible to have a "mixed" SQL Insert like the following?
I want to be able to get one value from another table (that needs a param) and then enter in 2 more params.
$sql = "INSERT INTO tblquestions (userID, questionText, questionAnswer) VALUES (
Select userID FROM tblusers WHERE userEmail = (?),?,?)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'sss', $userEmail, $question, $answer);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
throw new Exception($conn->error);
}
It is unnecessary. Just use insert . . . select:
INSERT INTO tblquestions(userID, questionText, questionAnswer)
Select userID, ?, ?
FROM tblusers
WHERE userEmail = (?);

DropDown Isset IF statement to move entire record MySQL

I'm new to php. I have a dropdown option. I want to put an if statement that if one of the options is selected e.g. 'Completed' then I would like it to get the entire record from the MySQL table and move it to another table with the same table structure.
This is what i have so far:
<?php
if( $_GET['status'] = 'Completed' ):
$stmt = $con->prepare("INSERT INTO second_table select * from first_table where id = id;
status = ?,
day_id = ?,
eta = ?,
c_notes = ?
WHERE booking_id = ?");
$stmt->bind_param('sissi',
$_GET['status'],
$_GET['day_id'],
$_GET['eta'],
$_GET['notes'],
$_GET['id']
);
$stmt->execute();
$stmt->close();
?>
If the two tables have the same structures I think your query should be
$stmt = $con->prepare("INSERT INTO second_table VALUES (SELECT * FROM first_table WHERE id = ?");
$stmt->bind_param('i', $_GET['id'] );
Let me know if this didn't work.

Categories