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));
Related
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 = ?
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);
}
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);
I'm trying to understand where I am wrong with this query..
$query = "INSERT INTO turni (data, utenteId, turno_ceduto, tipo_turno_ceduto,
turno_cercato,
note, date) VALUES (?, ?, ?, ?, ?, ?, NOW())";
$stmt = mysqli_prepare($dbc,$query);
mysqli_stmt_bind_param($stmt,'sissss', $data, $utenteId, $turno_ceduto,
$tipo_turno_ceduto, $turno_cercato, $note);
mysqli_stmt_execute($stmt);
$count = mysqli_stmt_affected_rows($stmt);
Why is $count -1??
Question
Why is $count -1??
Answer
-1 indicates that the query has returned an error
mysqli_stmt_affected_rows
You shoud check errors with mysqli_error, it's returns a string description of the last error.
You get the error description from the last mysqli-function, not from the last mysql-error.
You should always check for errors after each prepare() and execute(), and report the errors.
Here's an example:
if (($stmt = mysqli_prepare($dbc,$query)) === false) {
trigger_error(mysqli_error($dbc), E_USER_ERROR);
}
mysqli_stmt_bind_param($stmt,'sissss', $data, $utenteId, $turno_ceduto,
$tipo_turno_ceduto, $turno_cercato, $note);
if (mysqli_stmt_execute($stmt) === false) {
trigger_error(mysqli_stmt_error($stmt), E_USER_ERROR);
}
$count = mysqli_stmt_affected_rows($stmt);
When working with the sqlsrv_query command I can request data from the MSSQL server.
This works
But!
When I want to add data it returns the error [error:array].
The code I use for this is:
$tsql= "INSERT INTO dbo.VERLOF_events (id,
username,
soort,
afdeling,
description,
evdate,
trdate)
VALUES
(?, ?, ?, ?, ?, ?, ?)";
$var = array('', $username, $soort, $afdeling, $description, $evdate, $trdate);
if (!sqlsrv_query($conn, $tsql, $var))
{
die('Error: ' . sqlsrv_errors());
}
echo "1 record added";
The array values are set in the POST statement.
$afdeling = $row['Afdeling'];
$submit = #$_POST['submit'];
$description = #$_POST["description"];
$evdate = #$_POST["evdate"];
$trdate = #$_POST["trdate"];
$username = #$_SESSION['username'];
$soort = #$_POST['Dagen'];
Why does it return the array error?
I looked it up but could not find the problem returning the error.
Any help is appreciated!
The problem is probably you're trying to add an empty value in the id field. If you set identity on it with auto-numbering, you don't need to include it in your query :
$tsql= "INSERT INTO dbo.VERLOF_events (
username,
soort,
afdeling,
description,
evdate,
trdate)
VALUES
(?, ?, ?, ?, ?, ?)";
$var = array($username, $soort, $afdeling, $description, $evdate, $trdate);
if (!sqlsrv_query($conn, $tsql, $var))
{
die('Error: ' . sqlsrv_errors());
}
echo "1 record added";