I am parsing an XML feed into a MYSQL table using simplexml_load_file(). Some of the variables are blank, I would like them to be actual NULL instead of NULL, or is there even a difference?
$xml = simplexml_load_file('cb.xml') or die ('Bad XML File');
foreach($xml->item as $item) {
$name = $item->name;
//Tried
if ($name == '') {
$name = 'NULL';
}
//And
if ($name == '') {
$name = NULL;
}
mysql_query("INSERT INTO cb (name) VALUES ('$name')");
This is because you're giving MySQL a string:
.... ('ANYTHING WITHIN QUOTES IS A STRING')
And the PHP null value, when "casted" to a string, becomes an empty string. So your first try gave ... ('NULL'), and now it gives ... ('').
You must use the NULL keyword inside the query, without quotes, to insert NULL into a database field.
mysql_query("INSERT INTO cb (name) VALUES (" . ($name == null ? "NULL" : "'$name'") . ")");
Oh, and as usual, take care not to get SQL-injected with your unprotected $name variable.
The second variable initialization is correct; the first is just the string 'NULL' (which is not special from PHP's viewpoint). However, you should be using prepared statements (MySQLi_STMT or PDOStatement. If you want to stick with the regular mysql extension, use mysql_real_escape_string
An example with PDO is:
$stmt = $pdo_con->prepare("INSERT INTO cb (name) VALUES (?);");
$stmt->execute(array($name));
This will handle nulls correctly, unlike your current string interpolation.
if you're using more than one value and shorthand if else does work then do this: (we will insert the null data in column 3) * Notice that the single quotes are omitted.. this is because "NULL" cannot be entered in as a string for sql or else it will be a string NULL not an SQL NULL which is what we want.
//condition
if ($col3_var !== NULL)
$col3_var = "'$col3_var'";
else
$col3_var = "NULL"; //SQL will omit the "" here
$sql = "INSERT INTO tablename
(col1, col2, col3...)
VALUES
('$col1_var', '$col2_var', $col3_var)";
$result = mysql_query($sql) or die("Err: " . mysql_error());
Related
i want to check if a variable from $_POST is empty and INSERT a NULL to my Database.
But when I do it my way i always get a String called NULL and not a real NULL in my data set.
This is how I tried it:
if(isset($_POST['folge'])){
$comment = !empty($_POST['comment']) ? "'".$_POST['comment']."'" : null;
$sqlstring = "INSERT INTO eventstest (comment) VALUES (".$comment.")";
echo $sqlstring;
if ($mysqli->query($sqlstring) === TRUE) {
printf("Table myCity successfully created.\n");
}else{
printf("Errorcode: %d\n", $mysqli->errno);
printf("Error: %d\n", $mysqli->error);
}
if I send the form without making inputs to "comment" page output is:
INSERT INTO eventstest (comment) VALUES ()Errorcode: 1136 Error: 0
Whats wrong? Or whats the better way to check for empty inputs and add NULL to DB?
PS: The database cell has STANDARD: NULL
If you want to insert a NULL value into MySQL, you have to pass a null-value in the SQL query, not the string of null. It will still be a string from a PHP perspective, but not from the MySQL perspective.
if (!empty($_POST['comment'])) {
$comment = "'".$mysqli->real_escape_string($_POST['comment'])."'";
} else {
$comment = "NULL";
}
You can also shorten that into a one-liner, using a ternary operator
$comment = !empty($_POST['comment']) ? "'".$mysqli->real_escape_string($_POST['comment'])."'" : "NULL";
Then, because you assign the quotes around the comment-string itself, as you should do, since you alternatively want to pass a null-value, you need to remove the single quotes surrounding the variable from the query. This would otherwise break it too, as you'd get ''comment''.
$sql = "INSERT INTO table (comment) VALUES (".$comment.")";
Of course this assumes that the column comment allows for null-values. Otherwise it will fail, in which case you should either insert empty strings or change the column to accept null values.
It should also be noted that this query is exposed to SQL injection attacks, and you should use an API that supports prepared statements - such as PDO or MySQLi, and utilize those to secure your database against these kinds of attacks. Using a prepared statement with MySQLi would look something like this. See how we supply a PHP null to the value in bind_param() if $_POST['comment'] is empty.
// Set MySQLi to throw exceptions on errors, thereby removing the need to individually check every query
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (isset($_POST['folge'])) {
// $comment = !empty($_POST['comment']) ? $_POST['comment'] : null; // Ternary operator
$comment = $_POST['comment'] ?? null; // Null coalescing operator, since PHP 7
$sql = "INSERT INTO eventstest (comment) VALUES (?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $comment);
$stmt->execute();
$stmt->close();
}
PHP Ternary Operator
How can I prevent SQL injection in PHP?
Several things wrong here. First is that you are using string concatenation instead of prepared statements. This leaves you open to SQL injection. I suggest you stop this project right now and return after learning to use PDO and prepared statements.
Secondly, 'NULL' != null you need to specify it as null
Last but not least, generally there isn't a need to explicitly check for null in postvars and then pass a null again. If the column type allows null and you do not pass in a non null value. null will be stored in it anyway
i have been trying to insert NULL to my database if the value of input is empty
but i still it insert empty and NULL string
Here's my code
this code returns blank
if (empty($_POST['caller'])){ $caller= NULL; }else{ $caller = mysqli_real_escape_string($con, $_POST['caller']);}
or this
$caller = mysqli_real_escape_string($con, $_POST['caller']);
$caller = !empty($caller_contact) ? "'$caller'" : NULL;
this code returns NULL string
$caller = mysqli_real_escape_string($con, $_POST['caller']);
$caller = !empty($caller_contact) ? "'$caller'" : 'NULL';
or this
if (empty($_POST['caller'])){ $caller= 'NULL'; }else{ $caller = mysqli_real_escape_string($con, $_POST['caller']);}
query
$sql_caller = "INSERT INTO `tblcall_info` VALUES ('','$save_inc_id','$call_time','$call_date','$caller','$caller_contact','$receiver','$device')";
i have also tried changing '$caller' to $caller but its an error.
can anyone help?. thanks
You can try this way:
remove single invated comma from query and set them to query it will surely work for you
if (empty($_POST['caller'])){
$caller="NULL";
}else{
$caller=mysqli_real_escape_string($con, $_POST['caller']);
$caller="'$caller'";
}
$sql_caller = "INSERT INTO `tblcall_info` VALUES ('','$save_inc_id','$call_time','$call_date','$caller','$caller_contact','$receiver','$device')";
Try this method in the $sql_caller string:
INSERT INTO table_name (column1,column2,...) VALUES(value1,value2,...);
And skip the column & it's value, which you want to be set as NULL.
I have multiple if and elseif-statements like this:
if ($str == "CARS") {
$first = $db->prepare('INSERT INTO table_CAR (id_CAR, anything) VALUES (:id_CAR, :anything) ON DUPLICATE KEY UPDATE id_CAR = LAST_INSERT_ID(id_CAR)');
$first->bindParam(':id_CAR', $null = null, PDO::PARAM_NULL);
$first->bindParam(':anything', $anything, PDO::PARAM_STR);
$first->execute();
}
else if ($str == "PLANES") {
$first = $db->prepare('INSERT INTO table_PLANES (id_PLANES, anything) VALUES (:id_PLANES, :anything) ON DUPLICATE KEY UPDATE id_PLANES = LAST_INSERT_ID(id_PLANES)');
$first->bindParam(':id_PLANES', $null = null, PDO::PARAM_NULL);
$first->bindParam(':anything', $anything, PDO::PARAM_STR);
$first->execute();
}
Now I would like to make a function of that, because there is also done the same thing. The only difference are the names. But how can I put these words (CAR and PLANES) into variables? My problems are, that these words are part of queries and parameters and they aren't always the same (CARS != CAR).
You can always construct the sql query in a variable first:
function insert($table, $anything) {
// check $table using a whitelist to prevent SQL injections!
$sql = 'INSERT INTO table_' . $table . ' (anything) VALUES (:anything)';
$first->bindParam(':anything', $anything, PDO::PARAM_STR);
$first->execute();
}
As you can see, I cleaned up your query a bit. There's no need to insert a NULL value for AUTO_INCREMENT fields as MySQL will insert the correct value for you.
I'm trying to store an array into a table but its not working it adds the table but it doesn't add the column name at all. It's just empty
Here's the entire code.
<?php
include 'db.php';
if(isset($_GET['NAME'])) {
$sector = mysql_real_escape_string($_GET['SECTORPOSITION']) ; // escape your variable here .
$name = mysql_real_escape_string($_GET['NAME']) ; // escape your variable here .
mysql_query("INSERT INTO $sector (Name) VALUES ('$name') ") or die(mysql_error()) ;
}
if(isset($_GET['TYPE'])) {
file_put_contents('contents.txt', $_GET['TYPE'] . "\n", FILE_APPEND);
}
if(isset($_GET['ISEXPLORED'])) {
file_put_contents('contents.txt', $_GET['ISEXPLORED'] . "\n", FILE_APPEND);
}
if(isset($_GET['SECTORPOSITION'])) {
mysql_query("CREATE TABLE `".$_GET['SECTORPOSITION']."` ( Name VARCHAR(30), Type VARCHAR(30), IsExplored VARCHAR(30), SectorPosition VARCHAR(30), guid VARCHAR(30))");
}
if(isset($_GET['GUID'])) {
file_put_contents('contents.txt', $_GET['GUID'] . "\n", FILE_APPEND);
}
print('Added!');
?>
'RESOLVED THANKS TO ECHO'
'move the code of creating table first then insert to that table. you are inserting then creating table , you should do the opposite.'
Problem 2
Hey guys. I'm having an issue when I do
/test/test.php?SECTORPOSITION=13137&NAME=hibb&TYPE=Cluster&ISEXPLORED=true&GUID=13 I get a syntax error.
But when I do
?SECTORPOSITION=hey&NAME=hibb&TYPE=Cluster&ISEXPLORED=true&GUID=13 It works fine?
Here's my code.
<?php
include 'db.php';
if(isset($_GET['SECTORPOSITION'])) {
mysql_query("CREATE TABLE `".$_GET['SECTORPOSITION']."` ( Name INT, Type VARCHAR(30), IsExplored VARCHAR(30), SectorPosition INT, guid INT)");
}
if(isset($_GET['TYPE'])) {
$sector = mysql_real_escape_string($_GET['SECTORPOSITION']) ; // escape your variable here .
$type= mysql_real_escape_string($_GET['TYPE']) ; // escape your variable here .
$name = mysql_real_escape_string($_GET['NAME']) ; // escape your variable here .
$isexplored = mysql_real_escape_string($_GET['ISEXPLORED']) ; // escape your variable here
$guid = mysql_real_escape_string($_GET['GUID']) ; // escape your variable here
mysql_query("INSERT INTO $sector (Name,Type,IsExplored,SectorPosition,guid) VALUES ('$name','$type','$isexplored','$sector','$guid') ") or die(mysql_error()) ;
}
print('Added!');
?>
you can do like this
look like I have an array
$array = array(1,2,3,4);
json_encode($array);
and save the json encoded value
Its not standard to store array in db. You could see any cms, they would store it as json encoded objects, so that they can retrieve back the values
Dont use mysql_ functions anymore (its a sin!), use the improved. Use mysqli_. Like this:
$con = new mysqli('localhost', 'username', 'password', 'database');
if(isset($_GET['NAME'])) {
$your_table_whitelist = array('table1', 'table2'); // list your tables
if(!in_array($_GET['SECTORPOSITION'], $your_table_whitelist, true)) {
exit; // no table like that found
}
$stmt = $con->prepare("INSERT INTO {$_GET['SECTORPOSITION']} (Name) VALUES(?)");
$stmt->bind_param('s', $_GET['NAME']);
$stmt->execute();
}
Things to point out:
your current code is open to SQL injections, use MYSQLI and utilize parameterized queries instead.
since you cannot bind tables inside, just create a whitelist of table to compare to your variable which will hold the table name. If it matches, its okay, it's not, just handle that error.
your code is very open to sql injection you should go to mysqli or pdo.
if(isset($_GET['NAME'])) {
$sector = mysql_real_escape_string($_GET['SECTORPOSITION']) ; // escape your variable here .
$name = mysql_real_escape_string($_GET['NAME']) ; // escape your variable here .
mysql_query("INSERT INTO $sector (Name) VALUES ('$name') ") or die(mysql_error()) ;
}
EDIT: you got this error
Table 'TheGalaxy.at' doesn't exist
because you are creating table after the insert , so the table is not created yet.
Please do not use mysql function as they're deprecated, instead use mysqli.
the proper way to insert data into the database as follows :
mysqli_query($link, "INSERT INTO tableName values('".$_GET['NAME']."')");
where $link is your connection string. like
$link = ("myhost","myUser","myPassword","myDB");
Hope this will help.
if(isset($_GET['NAME'])) {
$sql= "INSERT INTO ".$_GET['SECTORPOSITION']."(name) VALUES(".$_GET['NAME'].")";
mysql_query($sql);
}
In a mysqli prepared statement, a NULL gets turned into '' (in the case of a string) or 0 (in the case of an integer). I would like to store it as a true NULL. Is there any way of doing this?
It's possible to bind a true NULL value to the prepared statements (read this).
You can, in fact, use mysqli_bind_parameter to pass a NULL value to the database. simply create a variable and store the NULL value (see the manpage for it) to the variable and bind that. Works great for me anyway.
Thus it'll have to be something like:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
// person is some object you have defined earlier
$name = $person->name();
$age = $person->age();
$nickname = ($person->nickname() != '') ? $person->nickname() : NULL;
// prepare the statement
$stmt = $mysqli->prepare("INSERT INTO Name, Age, Nickname VALUES (?, ?, ?)");
$stmt->bind_param('sis', $name, $age, $nickname);
?>
This should insert a NULL value into the database.
For anyone coming looking at this because they are having problems binding NULL in their WHERE statement, the solution is this:
There is a mysql NULL safe operator that must be used:
<=>
Example:
<?php
$price = NULL; // NOTE: no quotes - using php NULL
$stmt = $mysqli->prepare("SELECT id FROM product WHERE price <=> ?"); // Will select products where the price is null
$stmt->bind_param($price);
?>
The comments to the PHP documentation on mysqli_stmt::bind_param indicate that passing in NULL was not easily possible.
Please see #creatio's answer: https://stackoverflow.com/a/6892491/18771
Solutions offered in the comments do some pre-preparation work on the prepared statement, replacing the "?" markers with "NULL" for every param that has the PHP null value. The modified query string is then used.
The following function is from user comment 80119:
function preparse_prepared($sQuery, &$saParams)
{
$nPos = 0;
$sRetval = $sQuery;
foreach ($saParams as $x_Key => $Param)
{
//if we find no more ?'s we're done then
if (($nPos = strpos($sQuery, '?', $nPos + 1)) === false)
{
break;
}
//this test must be done second, because we need to
//increment offsets of $nPos for each ?.
//we have no need to parse anything that isn't NULL.
if (!is_null($Param))
{
continue;
}
//null value, replace this ? with NULL.
$sRetval = substr_replace($sRetval, 'NULL', $nPos, 1);
//unset this element now
unset($saParams[$x_Key]);
}
return $sRetval;
}
(It's not really the coding style I would have done it in, but if it works...)
I store all parameters in an array and pass them in bind_param function using array_shift($myArray). NULL is accepted like that.
<?php
$mysqli=new mysqli('localhost','root','','test');
$mysqli->query("CREATE TABLE test_NULL (id int(11))");
if($query=$mysqli->prepare("insert into test_NULL VALUES(?)")){
$query->bind_param('i',$null); //note that $null is undefined
$query->execute();
}else{
echo __LINE__.' '.$mysqli->error;
}
?>