Query executed, but data not saved into database PHP/SQL - php

I'm trying to execute a SQL query that saves POST data into the database. The data comes in correctly, and the arrays that are coming with the POST data are converted to strings.
When the query gets executed the message 'Succesfully saved into database' appears, however the data isn't visible in the database, so there must be a little mistake inside my code, however I can't seem to find it.
See my code below:
//database connection file
require "includes/dbh.inc.php";
foreach ($_POST as $post_var){
$obj = json_decode($post_var);
//Convert arrays to string
$userLikes = implode("|", $obj->userLikes);
$userEvents = implode("|", $obj->userEvents);
$userPosts = implode("|", $obj->userPosts);
$sql = "INSERT INTO visitor_data (id, fb_id, name, location, likes, events, posts) VALUES (NULL, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: dom.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ssssss", $obj->userId, $obj->userName, $obj->userLocation, $userLikes, $userEvents, $userPosts);
mysqli_stmt_execute($stmt);
echo '<p>Succesfully saved into database</p>';
exit();
}
}
This is how the database looks like
Thanks in advance!

You should not assume that the query ran successfully because an exception was not thrown. You need to consider what the function returns and how many rows are affected before knowing if it ran successfully or not. Update your code to this and figure out what is going on:
Also check to make sure you are not just updating the same row over and over.
//database connection file
require "includes/dbh.inc.php";
foreach ($_POST as $post_var){
$obj = json_decode($post_var);
//Convert arrays to string
$userLikes = implode("|", $obj->userLikes);
$userEvents = implode("|", $obj->userEvents);
$userPosts = implode("|", $obj->userPosts);
$sql = "INSERT INTO visitor_data (id, fb_id, name, location, likes, events, posts) VALUES (NULL, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: dom.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ssssss", $obj->userId, $obj->userName, $obj->userLocation, $userLikes, $userEvents, $userPosts);
if ( mysqli_stmt_execute($stmt) ) {
echo '<p>Succesfully saved into database</p>';
} else {
printf("Error: %s.\n", mysqli_stmt_error($stmt) );
}
}
mysqli_stmt_close($stmt);
}

Related

How do I fix the error when updating information in a MySQL table? [duplicate]

This question already has an answer here:
Is there an error when I try to update information in my table?
(1 answer)
Closed 3 years ago.
I'm having some problems trying to work out how to update a MySql table with my php code. This is the section so far, the code should either update the table or add a new column depending on weather an new column has already been made in the database on that date.
Edit: this is a lot of code, just to give context to what I am trying to do, the part of code throwing the error is shown separately below as well :)
$sql = "SELECT * FROM $username WHERE day=?;";
// Here we initialize a new statement by connecting to the database (dbh.php file)
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error the user is sent to the enter data page again
header("Location: ../enterTodaysData.php?error=sqlerror");
exit();
}
else { //if there are no errors...
mysqli_stmt_bind_param($stmt, "s", $day); //binds the parameters to the statement
mysqli_stmt_execute($stmt); //executes the statement
$result = mysqli_stmt_get_result($stmt); //saves the result of the statement into the result variable
if ($row = mysqli_fetch_assoc($result)) { //if the user HAS already made an entry that day
$sql = "UPDATE $username SET (peakflow1, peakflow2, coughing, tightChest, shortBreath, wheezing, symptomOne, symptomTwo, medication, mood, comments, overall WHERE day) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error the user is sent to the enter data page again
header("Location: ../enterTodaysData.php?error=sqlerror");
exit();
}
else { //if there are no errors...
mysqli_stmt_bind_param($stmt, "iisiiiiiiiiss", $peakflow1, $peakflow2, $coughing, $tightChest, $shortBreath, $wheezing, $symptomOne, $symptomTwo, $medication, $mood, $comments, $overall, $day);
mysqli_stmt_execute($stmt); //executes the statement
echo "<script type='text/javascript'>alert('Data entered successfully!');</script>";
header("Location: ../home.php?sql=success");
exit();
}
}
else{ //if the user has not
$sql = "INSERT INTO $username (day, peakflow1, peakflow2, medication, mood, coughing, tightChest, shortBreath, wheezing, symptomOne, symptomTwo, overall, comments) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; //the question marks are placeholders
$stmt = mysqli_stmt_init($conn);
//an sql statement is prepared and the database is connected to
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error the user is sent back to the signup page
header("Location: ../enterTodaysdata.php?error=sqlerror");
exit();
}
else {
//binds the paramaters and data to the statement
mysqli_stmt_bind_param($stmt, "siisiiiiiiiis", $day, $peakflow1, $peakflow2, $medication, $mood, $coughing, $tightChest, $shortBreath, $wheezing, $symptomOne, $symptomTwo, $overall, $comments);
//this executes the prepared statement and send it to the database, this registers the user.
mysqli_stmt_execute($stmt);
//sends the user back to the signup page, with a message confirming that it was a success
echo "<script type='text/javascript'>alert('Data entered successfully!');</script>";
header("Location: ../home.php?sql=success");
exit();
}
}
}
This is the part of code that the error is coming from:
$sql = "UPDATE $username SET (peakflow1, peakflow2, coughing, tightChest, shortBreath, wheezing, symptomOne, symptomTwo, medication, mood, comments, overall WHERE day) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
This is the error I am currently getting:
Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(peakflow1, peakflow2, coughing, tightChest, shortBreath, wheezing, symptomOne, ' at line 1 in C:\Users\MMRUD\Documents\XAMPP\htdocs\AsthmaAssistant\php_code\todaysdata.php:47 Stack trace: #0 C:\Users\MMRUD\Documents\XAMPP\htdocs\AsthmaAssistant\php_code\todaysdata.php(47): mysqli_stmt_prepare(Object(mysqli_stmt), 'UPDATE test SET...') #1 {main} thrown in C:\Users\MMRUD\Documents\XAMPP\htdocs\AsthmaAssistant\php_code\todaysdata.php on line 47
Your update syntax is wrong, it looks like you've confused it with INSERT syntax. Instead of something like this:
SET (Field1, Field2) = (?, ?)
you'd do something like this:
SET Field1 = ?, Field2 = ?

PHP Trying to insert data into two different tables using prepared statment

I've been working on this for a few days now and can not seem to find where i am going wrong, I imagine its something silly but as my university tutor has never used prepared statements before he has been of little to no use.
The first statement works a treat with no problems, the second doesn't input any of my data into my database. My goal is to take the information passed through the form (which i can include didn't want to bombard with information as i'm sure that is not the problem)and take the PictureID which is the primary key in my pictures table and insert this aswel as the other inforamtion into my pictureprice table.
any help would be welcomed, I'm fairly new to the site so be gentle please:)
<?php
include_once "dbh.php";
if (empty($imageTitle) || empty($imageDesc)) {
header("Location:changes.php?upload=empty");
exit();
} else {
$sql = "SELECT * FROM pictures;";
$sqltwo = "SELECT * FROM pictureprice;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: changes.php?sqlerror=failed");
exit();
} else { //Gallery order//
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setImageOrder = $rowCount + 1;
$sql = "INSERT INTO pictures (PhotographerID, PictureFolderPath,
imageDesc, imgFullNameGallery, orderGallery) VALUES (?, ?, ?, ?,
?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: changes.php?sqlerror=failedtoinputdata");
exit();
} else {
mysqli_stmt_bind_param($stmt, "issss", $_SESSION['PhotographerID'], $fileDestination, $imageDesc, $imageFullName, $setImageOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$photoID = $row["PictureID"]; //new
header("Location:changes.php?upload=success11");
}
$sqltwo = "INSERT INTO pictureprice
(PictureID, PictureSize, PictureSize2, PictureSize3, PictureSize4,
PicturePrice, PicturePrice2, PicturePrice3, PicturePrice4) VALUES (?,
?, ?, ?, ?, ?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sqltwo)) {
header("Location: changes.php?
sqlerror=failedtoinputdatapictureprice");
exit();
} else {
mysqli_stmt_bind_param($stmt, "issssiiii", $photoID, $picturesize1, $picturesize2, $picturesize3, $picturesize4, $price1, $price2, $price3, $price4);
mysqli_stmt_execute($stmt);
header("Location:changes.php?upload=success");
}
I think the problem is that the you are trying to get the photo ID from an INSERT statement...
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$photoID = $row["PictureID"]; //new
This probably won't fetching anything meaningful (as far as I can tell).
To get an auto increment value you would normally call...
$photoID = mysqli_insert_id($conn);

Inserting Multiple values into MySQL database using PHP

I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.

Insert query not inserting no error message

I can't get an INSERT query to INSERT in db. I am not getting any error message and was following a tutorial any help will be greatly appreciated.
$query = "INSERT INTO rooms (room_title,room_description,monthly_rate,prop_name,prop_description) VALUES ( ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($dbc,$query);
//$stmt = mysqli_query($dbc, $query);
if($stmt == false) {
die("<pre>".mysqli_error($dbc).PHP_EOL.$query."</pre>");
}
mysqli_stmt_bind_param($stmt,"ssiss",$pn,$d,$p,$ppn,$ppd);
mysqli_stmt_execute($stmt);
//mysqli_stmt_close($stmt);
// Check the results...
if (mysqli_stmt_affected_rows($stmt) == 1)
{
echo'<p>The room has been added.</p>';
// Clear $_POST:
$_POST = array();
}
mysqli_stmt_close($stmt);
} // End of $errors IF.
// End of the submission IF.
Because it does not echo "The room has been added" I suspect the problem is with the mysqli_stmt_affected_rows($stmt) == 1
try this
if ($stmt = mysqli_prepare($dbc, "INSERT INTO rooms (room_title,room_description,monthly_rate,prop_name,prop_description) VALUES ( ?, ?, ?, ?, ?)")) {
mysqli_stmt_bind_param("ssiss",$pn,$d,$p,$ppn,$ppd);
mysqli_stmt_execute($stmt);
} printf("Error: %s.\n", mysqli_stmt_error($stmt));

Mysqli Procedural Insert Into Table not working

I am trying to insert into a table with Procedural Mysqli. It is not posting any errors nor is it posting the information to the database. Here is my code:
$query = "INSERT INTO Accounts (FirstName, LastName, Username, Password, Access) VALUES ({$_POST['FirstNameTbx']}, {$_POST['LastNameTbx']}, {$_POST['UsernameTbx']}, {$_POST['PasswordTbx']}, {$_POST['AccessDDL']})";
mysqli_query($link, $query);
mysqli_close($link);
$Error .= "$query";
Update:
I changed to prepared statement, now I am getting:
Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables in /home/bryantrx/public_html/ec/add_user.php on line 19
There are only 5 variables that need to be bound, and the UserID auto increments, so it doesn't need to be bound or referenced in the statement..
if ($stmt = $link->prepare("INSERT INTO Accounts (FirstName, LastName, Username, Password, Access) VALUES (?, ?, ?, ?, ?)")){
$stmt->bind_param($_POST['FirstNameTbx'], $_POST['LastNameTbx'], $_POST['UsernameTbx'], $_POST['PasswordTbx'], $_POST['AccessDDL']);
$stmt->execute();
$Error .= "success";
$stmt->close();
} else {
echo $link->error;
}
To get an error message you need to call mysqli_error:
$error = mysqli_error($link);
You would also make life easier (and more secure) for yourself if you built your queries using prepare and parameters:
$query = "INSERT INTO Accounts (FirstName, LastName, Username, Password, Access)
VALUES ( ?, ?, ?, ?, ?)";
if ($stmt = mysqli_stmt_prepare($link, $query)) {
mysqli_stmt_bind_param($stmt, "sssss",
$_POST['FirstNameTbx'],
$_POST['LastNameTbx'],
$_POST['UsernameTbx'],
$_POST['PasswordTbx'],
$_POST['AccessDDL']);
if (!mysqli_stmt_execute($stmt)) {
$error = mysqli_stmt_error($stmt);
}
mysqli_stmt_close($stmt);
} else {
$error = mysqli_error($link);
}
mysqli_close($link);
UPDATE - ok, you've swapped to OO which is fine. When using bind_param the first parameter describes the data you are binding. In this case if it is five strings, you would put 5 "s" like so:
$stmt->bind_param("sssss",
$_POST['FirstNameTbx'],
$_POST['LastNameTbx'],
$_POST['UsernameTbx'],
$_POST['PasswordTbx'],
$_POST['AccessDDL']);

Categories