SQL UPDATE value as null or string - php

I searched almost whole internet, but could not find something similar, yet my question looks so simple.
I have a php code like so:
$id = 1;
if (!isset($_POST['port1'])) {
$port1 = null;
}
... which simply checks if submitted value is empty or not, if it is empty, then variable $port1 = null;
then, further in the code, I need to insert this value/update it in the database
$sql_update = ("UPDATE names_10 SET `digName1`=$port1 WHERE `device_id`='$id'");
...which should set the "digname1" to null. but it won't!
I tried every combination, every type of quotes, but every time I got UPDATE error..
any ideas?

Try this:
$id = 1;
if (!isset($_POST['port1'])) {
$port1 = "NULL";
}
$sql_update = ("UPDATE names_10 SET `digName1`= $port1 WHERE `device_id`='$id'");
I would rather suggest you to use PDO when you plan to bind something like this. There are a lot of benefits using PDO that would amaze you!

Related

Checking array data in sql condition PHP

I would like to UPDATE the seat_status to active by checking two conditions.
1st condition = bus_id
2nd condition = seat_title
I'm using this code in function cancelbook.
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
for($i=0;$i<count($seat_no);$i++)
{
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active' WHERE bus_id=:bus_id AND seat_title=:seat_title");
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',$seat_no[$i]);
}
if ($stmtactive->execute()) {
exit();
return true;
}
return false;
}
im getting this error
Notice: Array to string conversion
The way you did the loop will only update one row, to update every row you should execute your statement for each iteration.
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats
WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
foreach($seat_no as $seat) {
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active'
WHERE bus_id=:bus_id
AND seat_title=:seat_title");
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',$seat['seat_no']);
$stmtactive->execute();
}
}
it seems $seat_no[$i] is not string and it's an array , (I suggest var_dump($seat_no[$i]); it before), my quess is it should be something the following snippet:
use
$stmtactive->bindParam('seat_title',$seat_no[$i]['seat_no']);
instead of
$stmtactive->bindParam('seat_title',$seat_no[$i]);
in your code will resolved your problem.
of course, it's better instead of using for learn to use foreach
But another solution with better performance is using just one update instead of serveral updates!!!
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats
WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
$seat_numbers = array_values($seat_no);
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active'
WHERE bus_id=:bus_id
AND seat_title IN (:seat_title"));
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',implode(",",$seat_numbers));
$stmtactive->execute();
}
Also, remove Exit in your code, it's a bad mistake in your code

How to set a value in mysql to NULL using a variable?

I'm trying to set a variable to NULL if it's empty (after a form input) and update my db with it, but it keeps putting 0 in the field insted of NULL. (field is set to integer/NULL) I also tried $eloleg = "NULL" but that didn't work either.
if (!empty($_POST["eloleg"])) {
$eloleg = mysql_real_escape_string($_POST["eloleg"]);
}
else {
$eloleg = NULL;
}
mysqli_query($connection, "UPDATE $table SET eloleg='$eloleg' WHERE date='$eredeti_date'");
I think you wanted to do this:
$eloleg = 'NULL';
mysqli_query($connection, "UPDATE $table SET eloleg=$eloleg WHERE date='$eredeti_date'");
But as others have said, you should use a parametrized API to build your query, to avoid SQL injection as well as formatting pitfalls.

Why is my php "if statement" not affecting my mysql query?

First of all, I know mysql is deprecated. Will change to mysqli as soon as I figure out the issue at hand. My query continues to update all my rows even if the data is not set in the 'stripetoken' column. Why is this happening?
Code snippet:
$token_query = 'SELECT * FROM jobsubmission';
$token_res = mysql_query($token_query);
$token_row = mysql_fetch_array($token_res);
if(isset($token_row['stripetoken'])) {
$updqry = 'UPDATE jobsubmission SET assigned=1 WHERE ID="'.$book_ids[$jcount].'"';
$update = mysql_query($updqry);
$bookdate = date("d-m-Y");
Because $token_row['stripetoken'] is always set because it is a column in your database and it will be available in $token_row as a result. Now whether it has a value or not is a different story. You should be using empty() instead (assuming you don't want it to be true for falsy values).
if(!empty($token_row['stripetoken'])) {
So while #JohnConde was absolutely correct in saying I needed to use the empty function over the isset, my solution layed elsewhere. Here is how I managed to get the query to work to my specifications:
instead of searching for empty, I made the 'stripetoken' column NULL
by default.
This allowed me to use the following code:
$token_query = 'SELECT * FROM jobsubmission WHERE ID="'.$book_ids
[$jcount].'" and stripetoken is not null';
$token_res = mysql_query($token_query);
$token_row = mysql_fetch_object($token_res);
if(!$token_row->stripetoken == NULL) {

SQL Table not updating in PHP

I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows

How to only update an sql table column if a variable is not empty with php?

I am getting my variables from form fields using php :
$url=$_POST['url'];
$tags=$_POST['tags'];
$skillArea=$_POST['skill_area'];
$description=$_POST['description'];
$slideshowImageFileName=($_FILES['imageNameSlideshow']['name']);
But when I run my sql insert query, I get an error if one of the variables is empty, so I have taken to write if statements to deal with this to rewrite the query string, but surely, that's not the answer? It seems very messy
if(empty($slideshowImageFileName)){
$query1="INSERT INTO portfolio (item_name,image_path,description,url) VALUES('$itemName','$imageFileName','$description','$url')";
}else{
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
}
I suppose you are looking for something like this:
$slideshowImageFileName = (isset($_FILES['imageNameSlideshow']['name']) && !empty($_FILES['imageNameSlideshow']['name'])) ? $_FILES['imageNameSlideshow']['name'] : NULL;
This will check if the name of the slideshowimage is set and not empty. if it is NULL will be assigned to the variable, if its correct the value will be assigned.
You could replace NULL with "" if you want an empty string to be added.
Try to set the value of $slideshowImageFileName to empty string or a single space as your database table will accept, and use the second query always.
if(empty($slideshowImageFileName)){
$slideshowImageFileName = "";
}
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
I am agreed with Mr. Ray. But there is another solution apart from that. Probably slideshow_image_path field on the table doesn't allow null. So you may change the attribute by allowing null and it will work.
I'd probably construct a builder if I'm sure I'll get a lot of optional data.
Like this:
$acceptedKeys = array
('item_name',
'image_path',
'description',
'url',
'slideshow_image_path');
$inserts = array();
foreach($_GET as $key => $var) {
if(in_array($key, $acceptedKeys)) {
// clean and validate your keys here!
$inserts[$key] = $var;
}
}
$customKeys = implode(array_keys($inserts), ',');
$customValues = implode($inserts, ',');
$query = "INSERT INTO portfolio ($customKeys) VALUES($customValues)";
There's a few options to this.
Simplest one is to make sure the variables are always set, even if not passed through:
//Set up your database connection as normal, check errors etc.
$db = mysqli_connect($host,$user,$password,$db);
$url = isset($_POST['url']) ? mysqli_real_escape_string($db, $_POST['url']) : "";
$tags= isset($_POST['tags']) ? mysqli_real_escape_string($db, $_POST['tags']) : "";
Escaping data is good practice :) In your INSERT query you'll still need to wrap the values in quotes, or you could do that in the above code as per your preference.
http://uk3.php.net/manual/en/mysqli.construct.php

Categories