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

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);

Related

I want to use the INSERT statement to insert values that come from the SELECT statements in PHP

I want to use the INSERT statement to insert values that come from the SELECT statements in PHP
the table of student is not get the data
$sql = "INSERT INTO student(academic_major, promo, user_id) VALUES (?, ?, (?));";
$stmtt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmtt, $sql)){
header("Location: add_student_forum.php?error=sqlerrorstudent");
exit();
}else{
$id = "SELECT id FROM user WHERE email = '$email'";
mysqli_stmt_bind_param($stmtt, "sss", $academic_major, $promo, $id);
mysqli_stmt_execute($stmtt);
header("Location: add_student_forum.php?signup=success".$id);
exit();
}
when i execute it shows me this header header("Location: add_student_forum.php?signup=success".$id); in the url
and i dont know why the table is empty after
You don't bind SQL as a parameter. Bind the data as parameter and put the SELECT SQL in the prepared statement SQL
$sql = "INSERT INTO student(academic_major, promo, user_id) VALUES (?, ?, SELECT id FROM user WHERE email = ?);";
$stmtt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmtt, $sql);
mysqli_stmt_bind_param($stmtt, "sss", $academic_major, $promo, $email);
mysqli_stmt_execute($stmtt);
header("Location: add_student_forum.php?signup=success".$id);
exit();
Make sure you have mysqli error reporting enabled. How to get the error message in MySQLi?

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 = ?

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

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);
}

Inserting rows into mysql table fails

I have tried to write code that inserts fields into a database based on a SELECT query.
The following is my SELECT code
<?php
$sql = ("select * from category");
$result = $con->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$cat_id=$row['cat_id'];
$cat_title=$row['cat_title'];
echo "<option value=".$cat_id." >".$cat_title."</option>";
}
}
?>
this is my inserting script
$title = validateInput($_POST['title']);
$desc1 = validateInput($_POST['desc1']);
//$content = validateInput($_POST['content']);
$cat_title = validateInput($_POST['cat_title']);
$cat_id = validateInput($_POST['cat_id']);
$stmt = $con->prepare("INSERT INTO products (title,desc1,cat_title, img, img1,img2,img3,zip,user_id,cat_id) VALUES (?, ?, ?, ?,?,?,?,?,?,?,?)");
$stmt->bind_param("sssssssssss", $title, $desc1,$category,$img, $img1,$img2,$img3,$zip, $user_id,$cat_title,$cat_id);
if($stmt->execute()){
//echo "<script>alert('Your project added successfully');
echo "<script>alert('Your project added successfully ')</script>
<script>setTimeout(\"self.history.back();\",0000);</script>";
}else{
echo "<script>alert('Failed added your project');</script>";
}
?>
You are inserting parameters that are missing in the INSERT parameters, you stipulate 11 fields but enter only 10. Replace your code with below:
$title = validateInput($_POST['title']);
$desc1 = validateInput($_POST['desc1']);
//$content = validateInput($_POST['content']);
$cat_title = validateInput($_POST['cat_title']);
$cat_id = validateInput($_POST['cat_id']);
$stmt = $con->prepare("INSERT INTO products (title,desc1,cat_title,img,img1,img2,img3,zip,user_id,cat_id) VALUES (?,?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("ssssssssss", $title,$desc1,$cat_title,$img, $img1,$img2,$img3,$zip,$user_id,$cat_id);
if($stmt->execute()){
//echo "<script>alert('Your project added successfully');
echo "<script>alert('Your project added successfully ')</script>
<script>setTimeout(\"self.history.back();\",0000);</script>";
} else {
echo "<script>alert('Failed added your project');</script>";
}
?>
The problem is right here:
$stmt = $con->prepare("INSERT INTO products (title,desc1,cat_title, img, img1,img2,img3,zip,user_id,cat_id) VALUES (?, ?, ?, ?,?,?,?,?,?,?,?)");
$stmt->bind_param("sssssssssss", $title, $desc1,$category,$img, $img1,$img2,$img3,$zip, $user_id,$cat_title,$cat_id);
This is your original code, the problem is is that your insert into products the $cat_title should be between $desc1 and $category.
This should work:
$stmt = $con->prepare("INSERT INTO products (title,desc1,cat_title, img, img1,img2,img3,zip,user_id,cat_id) VALUES (?, ?, ?, ?,?,?,?,?,?,?)");
$stmt->bind_param("ssssssssii", $title, $desc1,$cat_title,$img, $img1,$img2,$img3,$zip, $user_id,$cat_id);
You also only have ten columns but were trying to insert 11 columns worth of information.
You would have to parse the user Id and Cat ID as integer instead of string. Now this updated code should work. You would have to bind the parameter with ssssssssii

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));

Categories