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.
Related
I have a prepared statement to store in my db some data coming from an API:
$sql = "INSERT INTO `standings` (`league_id`, `season`, `position`, `team_id`, `played`, `playedathome`, `playedaway`, `won`, `draw`, `lost`, `numberofshots`, `yellowcards`, `redcards`, `goals_for`, `goals_against`, `points`)
VALUES (:league_id, :season, :position, :team_id, :played, :playedathome, :playedaway, :won, :draw, :lost, :numberofshots, :yellowcards, :redcards, :goals_for, :goals_against, :points)
ON DUPLICATE KEY UPDATE `league_id`=:league_id, `season`=:season, `position`=:position, `team_id`=:team_id, `played`=:played, `playedathome`=:playedathome, `playedaway`=:playedaway, `won`=:won, `draw`=:draw, `lost`=:lost, `numberofshots`=:numberofshots, `yellowcards`=:yellowcards, `redcards`=:redcards, `goals_for`=:goals_for, `goals_against`=:goals_against, `points`=:points";
$prep = $pdo->prepare($sql);
$prep->bindParam(':league_id', $league_id);
$prep->bindParam(':season', $season);
$prep->bindParam(':position', $position);
$prep->bindParam(':team_id', $team_id);
$prep->bindParam(':played', $played);
$prep->bindParam(':playedathome', $playedathome);
$prep->bindParam(':playedaway', $playedaway);
$prep->bindParam(':won', $won);
$prep->bindParam(':draw', $draw);
$prep->bindParam(':lost', $lost);
$prep->bindParam(':numberofshots', $numberofshots);
$prep->bindParam(':yellowcards', $yellowcards);
$prep->bindParam(':redcards', $redcards);
$prep->bindParam(':goals_for', $goals_for);
$prep->bindParam(':goals_against', $goals_against);
$prep->bindParam(':points', $points);
foreach($result->TeamLeagueStanding as $standing){
$team_id = $standing->Team_Id;
$played = $standing->Played;
$playedathome = $standing->PlayedAtHome;
$playedaway = $standing->PlayedAway;
$won = $standing->Won;
$draw = $standing->Draw;
$lost = $standing->Lost;
$numberofshots = $standing->NumberOfShots;
[etc...]
$prep->execute() or print("PDO execute error: ".$prep->errorInfo()[2]);
The problem is that some leagues don't provide the NumberOfShots value, so $standing->NumberOfShots is an empty string, causing the error:
PDO execute error: Incorrect integer value: '' for column 'numberofshots' at row 1
And that row doesn't get inserted.
How can I make something like
if($numberofshot == "")
$numberofshot = NULL;
or tell PDO to use the default value instead of throwing an error, if the value is incorrect?
http://php.net/manual/en/pdo.setattribute.php
try:
setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
If this parameter needs an integer value then you should cast it to integer
like using intval() function.
$numberofshots = intval($standing->NumberOfShots);
If some string comes in $standing->NumberOfShots it will convert it into number that is 0
The below prepared statement doesn't insert into the database.
$sid =1;
$sid2 = $GET['sid2']; //empty
$position = 0;
$name = "John";
$new = $connectdb->prepare("INSERT INTO `table1` VALUES ('',:sid,:sid2,:position,:name)");
$new->execute(array(':sid'=>$sid,':sid2'=>$sid2,':position'=>$position,':name'=>$name));
When i add quotations to execute array values, then the insert works.
$new->execute(array(':sid'=>"$sid",':sid2'=>"$sid2",':position'=>"$position",':name'=>"$name"));
What i want to know is by adding quotations does this affect PDO's sanitization?
The only difference in your case is $sid2 and "$sid2".
If $sid2 is a string, then $sid2 is same with "$sid2", but when $sid2 is null, then thing changed. If $sid2 is null, then "$sid2" will be empty string "".
If your column for sid2 has NOT NULL constraint, then you will failed to insert a null value, but you could insert empty string.
Myabe you should try to:
$new->execute(
array(
':sid'=>$connectdb->quote($sid),
':sid2'=>$connectdb->quote($sid2),
':position'=>$connectdb->quote($position),
':name'=>$connectdb->quote($name),
)
);
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());
How do you check if a columns value is null? Example code:
$db = DBCxn::getCxn();
$sql = "SELECT exercise_id, author_id, submission, result, submission_time, total_rating_votes, total_rating_values
FROM submissions
LEFT OUTER JOIN submission_ratings ON submissions.exercise_id=submission_ratings.exercise_id
WHERE id=:id";
$st = $db->prepare($sql);
$st->bindParam(":id", $this->id, PDO::PARAM_INT);
$st->execute();
$row = $st->fetch();
$this->total_rating_votes = $row['total_rating_votes'];
if($this->total_rating_votes == null) // this doesn't seem to work even though there is no record in submission_ratings????
{
...
}
When you connect to the database, you can set some attributes to control how PDO handles Nulls and Empty Strings when they are returned by the database query
PDO::setAttribute (PDO::ATTR_ORACLE_NULLS, $option )
Where $option is one of the following:
PDO::NULL_NATURAL: No conversion.
PDO::NULL_EMPTY_STRING: Empty stringis converted to NULL.
PDO::NULL_TO_STRING: NULL is converted to an empty string.
Isnt it something like that that you want to do?
foreach($row as $r){
if($r->total_rating_votes == null){
//do something
}
Actually you might want to try:
if($r->total_rating_votes == ""){/*do something*/}
Because php might have converted the null value into an empty string, and then it's not actually null, it's ""
Hope this helps!
Thanks for all of your answers. After a bit of experimentation this code solved my problem
$this->total_rating_votes = $row['total_rating_votes'];
if(!isset($this->total_rating_votes)) // this is now true if this record had a NULL value in the DB!!!
{
...
}
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;
}
?>