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
Related
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 have the following in my PHP.
$stmt = $conn->prepare("INSERT IGNORE INTO savesearch (user, searchedFor, sortOrder, buildURLString, aspectFilters, oneSignalId, totalEntries)
VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $user, $searchedFor, $sortOrder, $buildURLString, $aspectFilters, $oneSignalId, $totalEntries);
// set parameters and execute
$user = $_POST['user'];
$searchedFor = $_POST["searchedFor"];
$sortOrder = $_POST["sortOrder"];
$buildURLString = $_POST["buildURLString"];
$aspectFilters = $_POST["aspectFilters"];
$oneSignalId = $_POST["oneSignalId"];
$totalEntries = $_POST["totalEntries"];
if ($stmt->execute()) {
$output->success = true;
echo json_encode($output);
} else {
$error->error = mysqli_error($conn);
echo json_encode($error);
}
However, IGNORE is not being picked up, it continues to add entries. Is there another good way to fix this?
Id like to see if the USER and the URL is the same, dont add, echo duplicate entry.
IGNORE is actually mostly for the opposite of what you want here. Instead, you can amend your MySQL table something like:
ALTER TABLE savesearch ADD UNIQUE KEY(user, buildURLString)
Then remove your IGNORE keyword
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 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.
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.