I have a problem with my PHP code, I can't get it to delete some data inside my MySQL database. I have tried some different things but it just won't work.
What iv'e tried: Deleting $productId, switched $producId to 1, 2, 3 and 4.
if (isset($_POST['remove_product'])) {
$productId = 4
$sql = "DELETE FROM products WHERE id = '.$productId.'";
$stmt = mysqli_init($conn);
if (!mysqli_prepare($stmt, $sql)) {
header("Location: products.php?error=sqlerror");
exit();
} else {
mysqli_execute($stmt);
}
}
I would like if it could delete the data from the MySQL table, so if someone could come with a solution, thanks : )
Thanks!
You are using the wrong functions to initialise, prepare and execute your statement. You should be using mysqli_stmt_init, mysqli_stmt_prepare and mysqli_stmt_execute instead. Also, since you are preparing a statement, you should take advantage of that to avoid SQL injection. Try this:
if (isset($_POST['remove_product'])) {
$productId = 4;
$sql = "DELETE FROM products WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: products.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, 'i', $productId);
mysqli_stmt_execute($stmt);
}
}
You are lacking a semicolon
$productId = 4
--------------^
Use
$productId = 4;
You have some issues with quotation marks:
$sql = "DELETE FROM products WHERE id = '.$productId.'";
-------^--------------------------------^------------^^
It should say:
$sql = "DELETE FROM products WHERE id = " . $productId;
Also you are not using prepared statements in the right way
if (isset($_POST['remove_product'])) {
$productId = 4;
$sql = "DELETE FROM products WHERE id = ?";
if (!$stmt = mysqli_prepare($sql)) {
header("Location: products.php?error=sqlerror");
exit();
} else {
$stmt->bind_params("i", $productId);
$stmt->execute();
}
}
There are some syntactic mistakes in your code. Use mysqli-query to execute the the query. it is used frequently
if (isset($_POST['remove_product'])) {
$productId = 4;
$sql = "DELETE FROM products WHERE id = ".$productId;
$stmt = mysqli_init($conn);
if (!mysqli_query($stmt, $sql)) {
header("Location: products.php?error=sqlerror");
exit();
} else {
mysqli_execute($stmt);
}
}
try this once
Related
<?php
require 'db.inc.php';
$Name = $_POST['Name'];
$NewHighScore = $_POST['HighScore'];
$sql = "SELECT * FROM CovidShooter;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: index.php?error0=sqlerror");
exit();
}
else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$n = 0;
while ($row = mysqli_fetch_assoc($result)) {
$HighScore.$n = $row['highscore'];
$Rank.$n = $row['Rank'];
echo $Rank.$n;
echo $HighScore.$n;
$n++;
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
If I put the echo statment between $Highscore and $Rank both values show. However when I put the $Highscore right in front of the $Rank it will show the highscore value for both $Rank & $Highscore. When I switch the the order it will only show Rank value for $Rank & $Highscore. Why is that? Am I doing something wrong or maybe I am ignorant of a rule set with SQL. I dont know. Please provide insight if you have any. Thank you,
You have to submit them after the cycle
while ( __SOMETHING $y__ ) {
$x .= $y;
}
echo $x;
I need help. I have a problem using multi query I want to put the last insert id in the next query the problem is it only adds one. Cart_id and qty has a multiple row. Please i need help thanks in advance.
Here is my code:
public function insertOrder($cart_id = null,$qty = null)
{
if (isset($cart_id)) {
$query = "INSERT INTO `tblsales`(`user_id`, `status`) VALUES ('23','delivery');";
$last_id = $this->db->con->insert_id;
$query .= "INSERT INTO `tblorders`(`sales_id`,`product_id`, `quantity`) VALUES ($last_id, {$cart_id},{$qty});";
$result = $this->db->con->multi_query($query);
if ($result) {
header("Location :" . $_SERVER['PHP_SELF']);
}
return $result;
}
}
Parameters inserting multiple values in each row
if (isset($_POST['cartid']) && $_POST['qty']){
foreach ($_POST["cartid"] AS $key => $item){
$result = $product->insertOrder($_POST['cartid'][$key], $_POST['qty'][$key]);
echo json_encode($result);
}
}
Tried you injecting a sql SELECT query between two insert methods?
public function insertOrder($cart_id = null,$qty = null){
if (isset($cart_id)) {
$query = "INSERT INTO `tblsales`(`user_id`, `status`) VALUES ('23','delivery');";
$last_id = getLastId("tablename");
$query .= "INSERT INTO `tblorders`(`sales_id`,`product_id`, `quantity`) VALUES ($last_id, {$cart_id},{$qty});";
$result = $this->db->con->multi_query($query);
if ($result) {
header("Location :" . $_SERVER['PHP_SELF']);
}
return $result;
}
}
Get last id function:
function getLastId($tablename){
$sql = "SELECT id FROM $tablename ORDER BY id DESC LIMIT 1";
//any necessary method, and $id = get sql result
return $id;
}
I want to update data in my database using php loop.
I have tried updating data, but it only updates the last record in my list and returns all the records as null/zero.
// attempting to update data
$rcount_student_lists = mysqli_query($mysqli, $count_student_lists);
while($row2 = mysqli_fetch_row($rcount_student_lists))
$student_count_count = $row2['0'];
for ($id = 1; $id <=$student_count_count; $id++)
{
$sql = "UPDATE exam_data SET score_s = '".${'dd_'.$id}."' WHERE exam_name_s = '".$one."'";
}
if (mysqli_query($mysqli, $sql)) {
echo juuhead("DETAILS UPDATED SUCCESFULLY");
} else {
echo "Error updating record: " . mysqli_error($mysqli);
}
I would want it to update all the records in the column score_s
You're generating the SQL string in a loop:
for ($id = 1; $id <=$student_count_count; $id++)
{
$sql = ...;
}
But you're only executing it once, because this is outside the loop:
if (mysqli_query($mysqli, $sql)) {
Move the query command inside the loop:
for ($id = 1; $id <=$student_count_count; $id++)
{
$sql = ...
if (mysqli_query($mysqli, $sql)) {
...
} else {
...
}
}
You're also missing braces on your while loop:
while($row2 = mysqli_fetch_row($rcount_student_lists))
$student_count_count = $row2['0'];
Without braces, the while only loops the one line following it. To loop over more than one line, you need to wrap the lines in braces:
while($row2 = mysqli_fetch_row($rcount_student_lists))
{
$student_count_count = $row2['0'];
for ($id = 1; $id <=$student_count_count; $id++)
{
...
}
}
Also, please read about SQL injection. Instead of building queries with string concatenation, use prepared statements with bound parameters. See this page and this post for some good examples.
if (isset($_POST["AddErrorCode"]))
{
$AddErrorCodeDB = $_POST["AddErrorCode"];
$AddErrorDescriptionDB = $_POST["AddErrorDescription"];
$AddQuantityDB = $_POST["AddQuantity"];
$AddStartDateDB = $_POST["AddStartDate"];
$AddCompletionDateDB = $_POST["AddCompletionDate"];
$AddReviewTypeDB = $_POST["AddReviewType"];
session_start();
$WO_ID = $_SESSION['SELECTED_WO_ID'];
if ($AddReviewTypeDB === 'PR')
{
$AddReviewerType = 'Peer Review';
$insert = "INSERT INTO `wo_errorinfo` (
`Error_Code` ,
`Error_Description` ,
`Error_Quantity` ,
`Review_Type` ,
`WO_NO`) VALUES (
'$AddErrorCodeDB' ,
'$AddErrorDescriptionDB' ,
'$AddQuantityDB' ,
'$AddReviewerType' ,
'$WO_ID')";
if ($AddCompletionDateDB === '')
{
//echo 'ritwik';
$status = 'Peer RWK';
$update = "UPDATE `associated_wos` SET `WO Status` = '$status' WHERE `ID` = '$WO_ID'";
}
else
{
//echo 'ritwik1';
$status = 'Peer Review Complete';
$update = "UPDATE `associated_wos` SET `WO Status` = '$status' WHERE `ID` = '$WO_ID'";
}
$sql = "SELECT * FROM `wo_reviewerqa` WHERE `WO_ID` = '$WO_ID' AND `reviewType` = '$AddReviewerType'";
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_num_rows($result);
//echo $num_rows;
if ($num_rows === 0)
{
//echo 'ritwik';
$insertreview = "INSERT INTO `wo_reviewerqa` (
`reviewType`,
`reviewStartDate`,
`reviewCompleteDate`,
`WO_ID`) VALUES (
'$AddReviewerType',
'$AddStartDateDB',
'$AddCompletionDateDB' ,
'$WO_ID')";
//echo $insertreview;
}
else
{
if ($AddStartDateDB !== '')
{
echo "<script type='text/javascript'>alert('Review Already Started, Start Date cant be changed');</script>";
}
}
if($conn->query($insertreview) === True)
{
echo "<script type='text/javascript'>alert('Start date updated successfully');</script>";
}
if ($conn->query($insert) === True)
{
echo "<script type='text/javascript'>alert('Error Code Submitted successfully');</script>";
}
}
All my condition are getting satisfied. I am even getting all the correct values in the echo but only the first insert query i.e. insert into 'wo_errorinfo' is working and all else are having no effect on the table. Can we not insert into multiple tables during a session. Is it due to session_start()? I have been trying to figure this out for more 1 day now but can't figure it.
You need to execute your statements, currently only $sql is executed.
You should also avoid building queries by concatenating strings as this will leave you vulnerable to SQL injection attacks where your users can modify your queries by passing special characters in the input. You should use mysqli::prepare, e.g:
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
}
I would like to update the status value -tinyint(1)- to activate and deactivate the user. Whenever I try to update I keep getting the message below which set to "Attendant update failed." Any help is appreciate it. Thanks
if (empty($errors)) {
// Perform Update
$id = $attendant["id"];
$status = mysql_prep($_POST["status"]);
$query = "UPDATE attendant SET ";
$query .= "status = '{$status}', ";
$query .= "WHERE id = {$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Attendant updated.";
redirect_to("activate_attendant.php");
} else {
// Failure
$_SESSION["message"] = "Attendant update failed.";
}
}
} else {
// This is probably a GET request
}
Remove the trailing comma in status = '{$status}', <=
MySQL would have thrown you an error by doing:
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
I would also like to note that your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.