Multiple rows update - update column NULL if blank field - php

I have a form that updates multiple row ids with 6 fields, I am trying to get the correct code to set the column to NULL if there is nothing changed.
Below is my code.
What I am trying to do is at the (shippedto_customer), the update works fine if I dont add in the if statement, but I want the if statement in case user does not change the date for the field shippedto_customer.
Sorry if I am not explaining correctly.
if(isset($_POST['Submit']))
{
$count=count($_POST["id"]);
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name SET status='" . $_POST['status'][$i] . "',
ship_from_factory='" . $_POST['ship_from_factory'][$i] . "',
shippedto_customer=if(shippedto_customer='',NULL,'" .
$_POST['shippedto_customer'][$i] . "'), ship_comments='" .
$_POST['ship_comments'][$i] . "' WHERE id='" . $_POST['id'][$i] . "'";
$result1=mysql_query($sql1);
}
}

You're testing the old shippedto_customer in the table, not the value from the form.
You can use the NULLIF() function to test if the value being stored is an empty string, and store NULL instead.
if(isset($_POST['Submit']))
{
$count=count($_POST["id"]);
for($i=0;$i<$count;$i++){
$status = mysql_real_escape_string($_POST['status'][$i]);
$ship_from_factory = mysql_real_escape_string($_POST['ship_from_factory'][$i]);
$shipped_to_customer = mysql_real_escape_string($_POST['shippedto_customer'][$i]);
}
$ship_comments = mysql_real_escape_string($_POST['ship_comments'][$i]);
$id = mysql_real_escape_string($_POST['id'][$i]);
$sql1="UPDATE $tbl_name
SET status='$staus', ship_from_factory='$ship_from_factory',
shippedto_customer=NULLIF('$shipped_to_customer', ''),
ship_comments='$ship_comments' WHERE id='$id'";
$result1=mysql_query($sql1);
}
}
If you're forced to use the old mysql extension, you need to escape all the parameters. I've shown that above. But as mentioned in the comments, you should migrate to a modern MySQL API (I recomment PDO) and use prepared statements. If you do this, a PHP null value will be converted automatically to SQL NULL when used as a parameter.

Related

wrong query inserting value in specific row

I'm trying to execute the following query where I want to add a value in the column firstime in the corresponding row with $netid and mac.
$query="INSERT INTO node WHERE netid='".$netid."' AND mac='" . $_GET['mac'] . "' (firstime) VALUES ('" . $firstcheck . "')";
mysql_query($query, $conn) or die("Error executing query: ".mysql_error($conn));
when I try I get the following error message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE netid='28' AND mac='24:A4:3C:40:4D:EB' (firstime) VALUES ('2014-01-16 12:0' at line 1
Any Idea??
You cannot use WHERE clause for INSERT query since it makes no sense
Here is a documentation page about its proper syntax: http://dev.mysql.com/doc/refman/5.6/en/insert.html
A scientific guess: what you need is UPDATE
Perhaps you want an update:
update node
set firsttime = '" . $firstcheck . "'
WHERE netid = '".$netid."' AND mac = '" . $_GET['mac'] . "';
insert inserts a new row into the table, not a new value into the row.
update updates a value in a row.
The WHERE conditions must go at after the colums and values declaration.
INSERT INTO node (firstime) VALUES ('" . $firstcheck . "') WHERE netid='".$netid."'
AND mac='" . $_GET['mac'] . "'";
Also use prepared statements and sanitize user submitted data, in order to prevent a SQL INJECTION which is a present and clear threaten.

Is it possible to update a table using WHERE email = $_SESSION['email']

I want to update an already existing table it only has email and I want to add first name and last name does this code work to do so?
UPDATE table
SET fname='$fname', lname='$lname'
WHERE email= '$_SESSION['email'].';
Or can I also use this
$sql="INSERT INTO $tbl_name(fname, lname)VALUES( '$fname, $lname')" WHERE email= '$_SESSION['email'].';
Your UPDATE has a syntax error (problem with apostrophes.)
INSERT will not update but multiply rows. That is not what you want to have.
Here is my suggested query:
$sql="UPDATE table SET fname='$fname', lname='$lname' WHERE email='".$_SESSION["email"]."'" ;
Fix your quotes, like so:
$sql="INSERT INTO $tbl_name(email) VALUES ( '" . $email . "') WHERE email = '" . $_SESSION['email'] . "'";
Try like this: In case of simple Update Query
$user_email = $_SESSION['email'];
$fname = 'Thierry';
$lname = 'Henry';
UPDATE table
SET fname='$fname', lname='$lname'
WHERE email= '$user_email';
Insertion is not a good idea here. It might duplicate your records.
If you want to be more specific than Go like this: Just providing your general syntax. No real time Syntax:
$user_email = $_SESSION['email'];
$fname = 'Thierry';
$lname = 'Henry';
$check_user = 'SELECT * FROM table WHERE email = "user_email"';
if($check_user)
{
YOUR UPDATE QUERY
}
else
{
YOUR INSERT QUERY
}
In case you are using mysql_ functions you should also escape the input:
$email = mysql_real_escape_string($_SESSION['email']);
Disclaimer for idiots: This does not imply I suggest to use mysql_* functions. Use mysqli or PDO instead.
You should also check against NULL and empty values in your query.
$sql = "REPLACE INTO " . $table . "
SET email='" . $email . "'
WHERE email='" . $email . "'
AND email IS NOT NULL
AND email != ''";
From http://dev.mysql.com/doc/refman/5.0/en/replace.html:
REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted.
Please don't downvote if this doesn't exactly fit, just use INSERT or UPDATE with the same syntax then.

Why am I having an issue passing an integer into a mysql query using a php variable?

I am running a php function with this line in it:
mysql_query("UPDATE `user-table` SET `$field` = '$value' WHERE `user_id` = $user_id");
For some reason this is not working. I have echoed out the $user_id variable, taken that integer and placed it in place of the variable in the query, so it looks like this:
mysql_query("UPDATE `user-table` SET `$field` = '$value' WHERE `user_id` = 11");
And it updated fine! So the issue must be something to do with the variable, but I can't figure out what.
Any thoughts?
It can depend on the settings in your php.ini. I can't remember the name of the environment variable, but if you build the string like so:
mysql_query("UPDATE `user-table` SET `$field` = '".$value."' WHERE `user_id` = ".$user_id.";");
It should work regardless of your php.ini settings, assuming you've already escaped your $value, and are sure your $user_id is an integer.
If you are assigning both the field (column) name & value to the variables $name & $value like that then;
field/column names aren't required to be in ticks. Therefore;
a) Change " SET `$field` to SET $field &
b) Change " `user-table` to user-table
Because you're quoting the entire sql statement, - "UPDATE..." - when you insert a
$variable into a string and its required to be quoted, you need to escape the
quotes or concatenate the string like:
"... = '" . $value . "' ... ";
You should probably also use a mysql_real_escape_string() on your variable to avoid
most common types of sql injection like:
"... = '" . mysql_real_escape_string($value) . "' ... ";
So, putting it all together, the following should work just fine:
mysql_query("
UPDATE user-table
SET $field = '" . mysql_real_escape_string($value) . "'
WHERE user_id = (int)$user_id
");
Hope it helps!
Gez
I was accidentally passing an undefined variable thinking it was an integer.
If I remember correctly, you should wrap variable into {}, because in your example you actually pushing $user_id as a string.
mysql_query("UPDATE `user-table` SET `$field` = '$value' WHERE `user_id` = {$user_id}");

mysql_insert_id() returning 0 even though the last insert was a success

$tSQL = "insert into events(title,start,end,allday,url,customerid) VALUES(\"" . $_POST['title'] . "\", FROM_UNIXTIME($epochstart), FROM_UNIXTIME($epochend), \"$allday\", \"$url\", \"$customerid\")";
$mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
$tSQL = "update events set url = \"details.php?\"" . mysql_insert_id() . " where idevents = \"$eventid\"";
$row = $mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
echo print_r($tSQL);
My insert statement for sure does insert the record however mysql_insert_id() keeps returning 0. It should not be this way because there is an auto incremented primary key in that events table and that is running fine as well. Any suggestions on how to get the last inserted ID?
Your query is executed via mysqli, so the mysql function would not hold the inserted ID. Instead, use the mysqli version:
$id = $mysqli->insert_id;
Becasue you are using mysqli and not mysql,
Simply replace mysql_insert_id() with mysqli_insert_id() if using Procedural style
Or replace it with $mysqli->insert_id if using Object Oriented Style
Since you are using mysqli extension, change
$tSQL = "update events set url = \"details.php?\"" . mysql_insert_id() . " where idevents = \"$eventid\"";
to
$tSQL = "update events set url = \"details.php?\"" .$mysqli->insert_id. " where idevents = \"$eventid\"";
Because your are using mysqli which is an improvement version of mysql.
Use mysqli->insert_id instead of mysql->insert_id()
$tSQL = "insert into events(title,start,end,allday,url,customerid) VALUES(\"" . $_POST['title'] . "\", FROM_UNIXTIME($epochstart), FROM_UNIXTIME($epochend), \"$allday\", \"$url\", \"$customerid\")";
$mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
$lastInsId=$mysqli->insert_id();
$tSQL = "update events set url = \"details.php?\"" . $lastInsId . " where idevents = \"$eventid\"";
$row = $mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
echo print_r($tSQL);

MySQL - Delete a row, how?

Can anyone show me a query in MySQL that would delete rows from all available columns.
I use this to insert rows:
$sql = "INSERT INTO " . KEYS . " // KEYS is a constant
(key, user_id, time, approved)
VALUES ('" . $randkey . "', '" . $user_id . "', '" . $time . "', '0')";
I need the opposite of this now, delete created rows.
delete from <table> where ....
Keep in mind that the delete statement is always for an entire row.
Using similar syntax sql = "DELETE FROM " . KEYS . " WHERE 1=1";
Replace 1=1 with the conditions for the row you want to delete or it will delete all rows.
Also, it's good to get out of the habit of just dropping variables into SQL as soon as possible, because it will open your code up to SQL Injection attacks. Look into using parameterized queries.

Categories