SQLite UPDATE submits null data if using data from $_POST - php

I'm trying to update a table in PHP with SQLite. My code is the following:
//Get params like this
$title = $_POST['title'];
...
$params = array($visible, $link, $title, $post, $month, $day, $year, $sub3);
$query = "UPDATE posts SET visible = ?, link = ?, title = ?, entries = ?, month = ?, day = ?, year = ? WHERE id = ?; COMMIT;";
$stmt = $db->prepare($query);
$result = $stmt->execute($params);
If I get the values from $_POST, by the time it does the execute on the statement, 99% of the time, null values are updated in the fields instead of the $_POST data ($sub3 is not from $_POST).
If I hard code the values, it works fine. I also have an insert statement in the same code path (checks to see if it's new data first, if not do the INSERT). Insert works fine every time (data from $_POST).
Also, I have code like this for three other tables, all of which work. This is the only table that doesn't. Nothing different about set up of table compared to others.
This one works on a different table:
$params = array($name, $username, $email, $level, $sub3);
$query = "UPDATE users SET name = ?, username = ?, email = ?, level = ? WHERE id = ?; COMMIT;";
$stmt = $db->prepare($query);
$result = $stmt->execute($params);
I've tried bindParam, bindValue, and creating the statement string manually without prepare, but as long as it's from $_POST, it won't work.
What am I missing? Anything else I can try?

Print the POST variables and check if it has the right data.
print_r($_POST);
EDIT:
Change the query.
//$params = array($visible, $link, $title, $post, $month, $day, $year, $sub3);
$query = "UPDATE posts SET visible = '$visible', link = '$link', title = '$title', entries = '$entries', month = '$month', day = '$day', year = '$year' WHERE id = $id; COMMIT;";
Make sure you have the correct $id

Related

PHP - using a variable as part of a column name in an INSERT INTO MySQL statement

I have a database set up and there are 2 different columns and I want to insert values into one of those two columns dynamically based on an ID that is passed in from $_GET. I have the bindParam variable part working, but I'm not sure how to use a variable in the INSERT INTO portion of the statement.
One column is called product1_vote and the other is product2_vote. I am getting the 1 or 2 from $_GET and I want to pass that into the prepare call to determine which column to update.
$productID = $_GET['id'];
$stmt = $pdo->prepare('INSERT INTO products (id, title, product1_vote)
VALUES(:id, :title, :product1_vote);
$id = $pdo->lastInsertId();
$title = 'Test';
$date = date('m/d/Y h:i:s', time());
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->bindParam(':product1_vote', $date, PDO::PARAM_STR);
How would I go about changing the INSERT INTO part to work dynamically instead of the current hardcoded product1_vote.
Something like this to give you an idea of what I'm after:
$stmt = $pdo->prepare('INSERT INTO products (id, title, product.$productID._vote)
VALUES(:id, :title, :product.$productID._vote);
$id = $pdo->lastInsertId();
$title = 'Test';
$date = date('m/d/Y h:i:s', time());
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->bindParam(':product.$productID._vote', $date, PDO::PARAM_STR);
You can't parameterise a column name, but also, to guard against SQL injection you don't want to allow direct user input into the query without validation.
A common solution to this is to make a "whitelist" of allowed values and ensure that the user-provided value matches one of them before including it in the query.
For example:
$productID = $_GET['id'];
$voteIDs = ["1", "2"];
if (!in_array($productID, $voteIDs)) {
echo "invalid input value";
die();
};
$stmt = $pdo->prepare('INSERT INTO products (id, title, product'.$productID.'_vote)
VALUES(:id, :title, :product1_vote);
P.S. It's possible this has arisen because your database could be better normalised. If you have multiple votes per product, consider storing them in a separate "productVotes" table with a foreign key back to the products table. Then you wouldn't need to vary the column names in your query.

Prepared Statement to Insert and update different table in database

Please How can i use prepared statement to update one table and insert into another table. i did what i no was right but the when i submit the form on that page, it just give me a blank page and nothing happened in the two database see what it look like
$check = "INSERT INTO users(userEmail, password, joinDate, recEmails,
isActive, hash, lastUpdated)
VALUES (?, ?, NOW(), 1, 0, ?, NOW() ) ";
$stmt = $mysqli->prepare($check);
$stmt->bind_param('sss',$emailAddy,$password,$hash );
$stmt->execute();
$stmt->close();
$check1="UPDATE pin SET status = '1', usedby = ?,WHERE pin = ?";
$stmt = $mysqli->prepare($check1);
$stmt->bind_param('ss',$emailAddy,$pin);
$stmt->execute();
$stmt->close();
The result i get is this example.com is currently unable to handle this request.
I have tried and discovered that the issue is hidden somewhere here, if i remove the update table instruction the code works fine but one i return the issue comes back. Please can anybody help?
You have an error here:
$check1 = "UPDATE pin SET status = '1', usedby = ?, WHERE pin = ?";
Change it to (Remove the , after usedby = ?)
$check1 = "UPDATE pin SET status = '1', usedby = ? WHERE pin = ?";

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.

Trouble Updating a Database Record

Here is prepare update statement and I think I Have the Variable types out of whack, not sure.
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE `Calibration_and_Inspection_Register` SET `item_type` = ?, `location` = ?, `date_last_test` = ?, `serial_number` = ?, `date_next_test` = ?, `comments` = ?
WHERE `id`=?"))
{
$stmt->bind_param("issdsds",`$id`, `$item_type`, `$location`, `$date_last_test`, `$serial_number`, `$date_next_test`, `$comments`);
$stmt->execute();
$stmt->close();
}
Order is important if you are not using named parameters. Since id is last parameter in the statement, it needs to be the last in the list of bound parameters as well.
Back-ticks around your parameter variables names in bind_param() call are also probably giving you errors. It should look like this:
$stmt->bind_param("ssdsdsi",$item_type, $location, $date_last_test, $serial_number, $date_next_test, $comments, $id);

Query isn't getting executed

Can some onw please explain what is wrong with this ... this worked completely fine with procedural php
function foo(){
$incomingtime = date('Y-m-d H:i:s', time());
$stmt = $db->stmt_init();
$id = "Abc123" ;
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$stmt->execute();
printf("Affected rows (UPDATE): %d\n", $db->affected_rows); // Always return 1
$stmt->close();
}
But nothing goes in the database.
Datatype in mysql db for indate is datetime
There's several issues with this code.
$stmt_4 is used before it's defined.
$u_id and $c_id are both defined then not used.
Trying to execute $stmt without supplying parameters.
$db is not defined.
$id is not defined.
If you are trying to convert working code to a function make sure that either the function gets these passed in as an argument, they are marked as global or the function creates/ retrieves them.
Check changing:
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$u_id = 1;
$c_id = 1;
$stmt->execute();
to:
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (CURRENT_TIMESTAMP, ?, ?, ?)"
$stmt = $db->prepare($query);
$stmt->execute(array($id, $u_id, $c_id));
NOTE: I deleted the parameter ssii because it's not considered in the query. It only expects 4 parameters.

Categories