MySQLI Update Statement not working - php

<?php
header('Content-Type: application/json');
include '../../connection.php';
$id_e = $_POST['id'];
$location_e = $_POST['location'];
$state_e = $_POST['state'];
$notes_e = $_POST['notes'];
$sql="UPDATE chassis SET location='%$location_e%', state='%$state_e%', notes='%$notes_e%' WHERE id='%$id_e%'";
$query = mysqli_query($db,$sql);
if (!$query) {
echo json_encode(["message"=>mysqli_error($db)]);
}else {
echo json_encode(["message"=>"Success"]);
}
/* I used this code below to check if the data sent by ajax is received
switch($state_e){
case "New":
echo json_encode(["message"=>"hi"]);
break;
default:
echo json_encode(["message"=>"nope"]);
break;
}
}*/
?>
Hi, I'm not sure what the problem with my code is but the UPDATE statement isn't updating my database. I have an ajax jquery posting data which is received by this PHP file. I know that the data is being received by the PHP file because I tried a the piece of code to check it. Also, the query is returning success. I think the problem lies with the UPDATE statement however, I've tried different variations of the UPDATE statement like:
$sql="UPDATE chassis SET location='".$_POST['location']."', state='".$_POST['state']."', notes='".$_POST['notes']."' WHERE id='".$_POST['id']."";
It still doesn't work. I also checked the privileges on the SQL and I have All privileges. Please help, I'm a high school student and this is for my end of year project. Cheers :)

You should be using prepared statements. Also i do not see the reason for adding the % next to the variables as per my comment. Also you should be getting the real error and not just outputting Error
$sql="UPDATE chassis SET location=?, state=?, notes=? WHERE id=?";
$result = $db->prepare($sql);
$result->bind_param('sssi', $location_e, $state_e, $notes_e, $id_e);
echo $result->execute() === true ? 'Success' : 'Failed: '.$result->error;

Related

Save button that can also update once the record is already saved on the database

I was wondering how to construct the correct syntax for the if-else statement, or if there's something missing in my code.
<?php
include "../dbcon.php";
session_start();
ob_start();
$sql = mysqli_query($con,"SELECT * FROM clientdocuments WHERE docID = $_POST[docID]");
$rows = mysqli_fetch_array($sql, MYSQLI_ASSOC);
//IF CSS input value is filled
if(!empty($_POST)){
$output = '';
$message = '';
$docID = mysqli_real_escape_string($con, $_POST["docID"]);
$docSIG_Contract = mysqli_real_escape_string($con, $_POST["docSIG_Contract"]);
//I don't get what this "if(isset($_POST["docID"])){" purpose (Sorry very new to php)
if(isset($_POST["docID"])){
if (!empty($docID)) {
$query = "UPDATE clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //UPDATE ONCE docID ALREADY EXIST ON THE DATABASE
} else {
$query = "INSERT INTO clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //INSERT IF THE docID doesn't exist yet
}
$str = mysqli_query($con,$query);
if(!$str){
echo 'FAILED';
}
}else{
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
}
}
?>
remove this if statment: if (!empty($docID)) {
Make sure that u send with each post update the "docID" value
if(isset($_POST["docID"])) statement checks to see whether the input with the name docID has a value.
if(!empty($_POST)) I am not sure whether this will work, my guess is that you are trying to check whether the request method is POST (if the save button was clicked). For this I use
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
I would then check to see whether docID has a value ie
(isset($_POST["docID"])) OR (!empty($_POST["docID"]))
Difference between isset and !empty
What's the difference between 'isset()' and '!empty()' in PHP?
If there is a value, $query would be the update statement
If there is no value $query would be the insert statement In this situation don't enter the DocID value (because then it would always be 0 which will also cause errors)
Hope that makes sense!

PHP MySQL record update error

I am wondering what mistakes has been made in this pretty simple update statement using old version of PHP. If I echo the statement it says update statement is getting form submitted properly.
Here is the code:
<?php
echo $q = "UPDATE notice SET FromDate = $notice_fromdate, ToDate = $notice_todate, VacType ='$notice_vactype',NoticeDetail ='$notice_detail',Status ='$notice_status' WHERE ID=$id";
if (mysql_query($link, $q)) {
echo "Record updated successfully";
} else {
echo "<h3>Error updating record</h3>". mysql_error($link)."-". mysql_errno($link). "\n";
}
?>
and the output returns this
UPDATE notice SET FromDate = 2017-01-08, ToDate = 2017-01-09, VacType ='May Day',NoticeDetail ='Testing',Status ='Enabled' WHERE ID=3
Error updating record
-0
I know its a pretty simple thing, I guess I have not made any mistake in the update statement but instead it is showing Error update record. I copied the output SQL statement and run at phpmyadmin, it has worked properly. It would be nice if you can help me. Thank in advance
Note: Clients website built on old version of PHP, I know that few functions got deprecated so it would be better if you do not discuss or criticize about the version.
Apply quotes to dates it will work
<?php
echo $q = "UPDATE notice SET FromDate = '$notice_fromdate', ToDate = '$notice_todate', VacType ='$notice_vactype',NoticeDetail ='$notice_detail',Status ='$notice_status' WHERE ID=$id";
if (mysql_query($link, $q)) {
echo "Record updated successfully";
} else {
echo "<h3>Error updating record</h3>". mysql_error($link)."-". mysql_errno($link). "\n";
}
?>

SQL database not inserting data?

I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.

mySQLi_affected_rows check not working, or is it...?

(Sorry, I don't really know what I am doing.)
I have this Unity game in an iframe on Facebook calling a php file in the same directory, and that much is working. What I want it to do is update the player record if it is there and make one if it isn't.
This script runs but it always returns a "not here" and when I check the database, it is in fact creating the records each time, identical but for the datetime field. So I don't understand why affected_rows is never coming back as "1".
<?php
$db = #new mysqli('••.•••.•••.••', '•••••••••••', '••••••••','•••••••••••');
if ($db->connect_errno)
{
echo("Connect failed "+mysqli_connect_error());
exit();
}
$inIP = $_POST["ip"];
$playerIP = mysqli_real_escape_string($db, $inIP);
$inUN = $_POST["un"];
$playerUN = mysqli_real_escape_string($db, $inUN);
$query = "UPDATE lobby SET whens=NOW(), wherefores='$playerIP', whys=0 WHERE whos='$playerUN'";
mysqli_query($db, $query);
if (mysqli_affected_rows($db) > 0)
{
echo "here";
}
else
{
$query2 = "INSERT INTO lobby (whens,whos,wherefores,whys) values (NOW(),'$playerUN','$playerIP',0)";
mysqli_query($db, $query2);
echo "not here";
}
if ($db)
{
$db->close();
}
?>
You have a typo:
wherefores=$playerip
it should be
wherefores=$playerIP
because of that
mysqli_affected_rows($db)
returns
-1
Sounds like you're experiencing the same problem as me, especially if you are running your code through a debugger. I've investigated the issue with Netbeans and Xdebug and it seems this is a bug in the MySQLi extension itself. An according bug report has been made. In the meantime you can instead use another expression, e.g.:
if (mysqli_sqlstate($dbc) == 00000) {
//your code
}
to continue debugging your remaining code.

Trouble with updating Data trough PHP

I have a problem with this code, it does delete a row but not editing one. I cannot figure out how to make it work.
Here's the script:
<?php
if($_POST['delete']){
$i = 0;
while(list($key, $val) = each($_POST['checkbox'])) {
$sql = "DELETE FROM $tbl_name WHERE id='$val'";
mysql_query($sql);
$i += mysql_affected_rows();
}
// if successful redirect to delete_multiple.php
if($i > 0){
echo '<meta http-equiv="refresh" content="0;URL=data.php">';
}
}
if($Submit){
for($i=0;$i<$count;$i++){
$sql="UPDATE $tbl_name SET naam='$naam[$i]', achternaam='$achternaam[$i]', leeftijd='$leeftijd[$i]', straat='$straat[$i]', postcode='$postcode[$i]', telefoon='$telefoon[$i]', email='$email[$i]', geslacht='$geslacht[$i]', pakket='$pakket[$i]', WHERE id='$id[$i]'";
$result1=mysql_query($sql1);
}
}
mysql_close();
?>
As others have pointed out $Submit isn't defined before the if statement - also $tbl_name isn't defined either so it would bring back an error if the if statement was triggered.
Also in $result1 you used $sql1 - $sql1 has not been defined.
You're vulnerable to SQL injections like Pekka said, so I advise reading up on it, always, ALWAYS validate user inputted data, never trust anyone :)
Also, you don't need to print a meta refresh, you can just use header
header ("Location: data.php");
$Submit is not defined before it is used. So, its value will be null which is a falsy value. Hence if loop will never get executed.
$Submit is not defined (as others already mentioned). Also, if you do define $Submit then $count is still undefined. So you still won't get into the for loop. And if $count is defined, your code still does not update the database. You store your sql query in $sql but pass $sql1 , which has not been set, as query that should be executed.
And your code is wide open for sql injection. You should not want that.

Categories