Insert NULL variable into database - php

I have variable set to NULL that im trying to insert into a database but for some reason they keep getting submitted as '0'. Im positive that column im trying to inset into allows NULL and that the default is set to to NULL. Heres my code:
$insert = NULL;
$query = mysql_query("INSERT INTO `table1` (column1) VALUES ('$insert')") or die(mysql_error());

Warning:
Please, don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi.
IF you want it to be NULL (and you really really still want to use mysqli_*) in the database you can do the following:
$insert = NULL;
$query = mysql_query("INSERT INTO `table1` (column1) VALUES ("
.(($insert===NULL)?
"NULL":
"'".mysql_real_escape_string($insert)."'").
")") or die(mysql_error());
But this could lead to nefarious SQL injection and is not recommended.
See Bobby Tables
So: all in all you should be using prepared statements.
You can use MySQLi like so:
$dbHandle = new mysqli(...);
$query = "INSERT INTO `table1` (column1) VALUES (?)";
$statement = $dbHandle->prepare($query);
if($statement){
$statement->bind_param('s', $insert);
if(!$statement->execute()){
echo "Statement insert error: {$statement->error}";
}
$statement->close();
}
else {
echo "Insert error: {$dbHandle->error}";
}

Try this for static query:
$query = mysql_query("INSERT INTO `table1` (column1) VALUES (NULL)") or die(mysql_error());
Using Variable :
$insert= NULL;
$insert = ($insert===NULL)? 'NULL' : "'$insert'";
mysql_query("INSERT INTO `table1` (column1) VALUES ($insert)") or die(mysql_error());

Try without the quotes;
$query = mysql_query("INSERT INTO `table1` (`column1`) VALUES (".$insert.")") or die(mysql_error());
The query should be;
INSERT INTO table1 (column1) VALUES (NULL);

Related

Data not inserting into database to a table

I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.

MY sql query not working fully

I am using to add data into DB. First i get the values from post and then insert it into table. The problem is that there are total 7 values but only 5 values added and 2 of them not inserted into the table. Here is my code
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
$degree_title = $_POST['degree_title'];
$degree_year = $_POST['degree_year'];
$uni_name = $_POST['uni_name'];
$degree_level = $_POST['degree_level'];
$major_sub = $_POST['major_sub'];
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
}
I echo the all values and all values are coming so why they all not inserted into table any idea. Thank
try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, '$eme_uid', '$degree_title', '$degree_year', '$degree_level', '$major_sub', '$uni_name')");
and i would highly recommend:
1) dont use mysql_ its deprecated, use mysqli_*
2) sanitze ALL values in _POST befor using in SQL statements.
if id is autoincrement then you dont need to insert it.
try this
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES ($eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
My guess is that $degree_title and $uni_name doesn't get inserted because they are varchars. In that case you will have to put quotes around these values.
Mysql is kind of "forgiving" in the sence that it does not throw an error when using incorrect types in the sql-statement in relation to the actual type of the column.
Try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, '$degree_title', $degree_year, $degree_level, $major_sub, '$uni_name')");
As mentioned before id doesn't have to be included (if id-column is autoincremental) in the insert-statement, and you should really learn mysqli or PDO.

MySQL now() in database

I'm trying to put the time of a post into my database table but i can't get it to work. maybe someone here can explain what i'm doing wrong.
This is my code:
<?php
if (isset($_POST['upload_message'])) {
$message_title = $_POST['message_title'];
$message_content = $_POST['message_content'];
}
$table_name = "posts";
$add_query = "INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', 'SELECT NOW()')";
if (mysql_query($add_query)) { //executes query and error check
echo "het artikel staat in de database";
}
else { //error message
echo "fout bij het toevoegen" . "<br />" . mysql_error();
}
?>
and this is a screen shot of my db table : http://gyazo.com/17019f143eab6e5818752c33824bde29
When I run mysql_error is get the following message :
Incorrect datetime value: 'SELECT NOW()' for column 'date' at row 1
You don't have to SELECT NOW(), just NOW()
$add_query = "INSERT INTO $table_name (name, content, date)
VALUES ('$message_title', '$message_content', NOW())";
You should use prepared statements with binded parameters using mysqli_ or PDO.
NOW() is a mysql function, you don't have to "select it" just call it.
Replace the "SELECT NOW()" for just "NOW()".
INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', 'NOW()')
Or you can use CURRENT_TIMESTAMP
INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', CURRENT_TIMESTAMP);
Mysql_query is deprecated as of PHP 5.5.0.
Use PDO or Mysqli !
And secure your code, we can do injection sql.

Where is the error in my sql code

$fname = addslashes($fname);
$lname = addslashes($lname);
$dob = addslashes($dob);
$email = $_POST['email'];
$sql =
"INSERT INTO subscriber
(fname, lname, dob)
VALUES
('".$fname."', '".$lname."', '".$dob."')
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");
I am getting error in sql query "insertion error". Query is inserting data into DB after removing WHERE statement. What is the error.
You can't use where in an insert statement. You might be thinking of an update instead?
$sql = "update subscriber set fname='".$fname."', lname = '".$lname."', dob = '".$dob."' WHERE email='".$email."'";
If your email is a unique value, you can also combine an insert with an update like this:
insert into
subscriber (fname, lname, dob, email)
values ('".$fname."', '".$lname."', '".$dob."', '".$email."')
on duplicate key update set fname='".$fname."', lname='".$lname."', dob='".$dob."'
This second syntax will insert a row if there isn't one with a matching email (again, this has to be set to a unique constraint on the table) and if there is one there already, it will update the data to the values you passed it.
Basically INSERT statement cannot have where. The only time INSERT statement can have where is when using INSERT INTO...SELECT is used.
The only syntax for select statement are
INSERT INTO TableName VALUES (val1, val2, ..., colN)
and
INSERT INTO TableName (col1, col2) VALUES (val1, val2)
The other one is the
INSERT INTO tableName (col1, col2)
SELECT col1, col2
FROM tableX
WHERE ....
basically what it does is all the records that were selected will be inserted on another table (can be the same table also).
One more thing, Use PDO or MYSQLI
Example of using PDO extension:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
?>
this will allow you to insert records with single quotes.
Oops !!!! You cannot use a WHERE clause with INSERT statement ..
If you are targeting a particular row then please use UPDATE
$sql = "Update subscriber set fname = '".$fname."' , lname = '".$lname."' , dob = '".$dob."'
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");

How to launch two sql queries using result of first one in second?

I have 2 queries and i want to use result of first query in second one.
Following does not work for me:
$id = $_GET['uid'];
$app_id = $_GET['apid'];
$sql = "insert into tbl_sc (client_id,status) values ($id,1)";
mysql_query($sql) or die ($sql);
$result = mysql_insert_id();
echo $result;
$sql = "insert into tbl_ms(m_name, ng_ID, status)
values ($app_id,$result ,1)";
$result = mysql_query($sql) or die ($sql);
Is there any other way to get same result?
You could have used MySQL LAST_INSERT_ID() function. This way all this mess with insert id will be gone.
$sql = "insert into tbl_sc (client_id,status) values ($id,1)";
if(mysql_query($sql)){
$sql = "insert into tbl_ms(m_name, ng_ID, status)
values ($app_id, LAST_INSERT_ID() ,1)";
$result = mysql_query($sql);
if($result){
// Process your result
}else{
// second query failed!
die (mysql_error());
}
}else{
// first query failed!
die (mysql_error());
}
$result contains an SQL resource, not the id.
$insert_id = mysql_insert_id();
$sql = "INSERT INTO tbl_ms(m_name, ng_ID, status)
VALUES ($app_id, $insert_id, 1)";
Don't forget to sanitize user input to avoid injection attacks.
$result in your code will always contain a boolean, and if it was successful, when used in the next query, this will always be 1. You echod the value you need, but you didn't catch it in a variable so it could be used in the next query.
Try this:
$id = mysql_real_escape_string($_GET['uid']);
$sql = "INSERT INTO tbl_sc
(client_id, status)
VALUES
($id, 1)";
mysql_query($sql) or die ("MySQL error with query ( $sql ): ".mysql_error());
$app_id = mysql_real_escape_string($_GET['apid']);
$insertId = mysql_insert_id();
$sql = "INSERT INTO tbl_ms
(m_name, ng_ID, status)
VALUES
($app_id, $insertId ,1)";
mysql_query($sql) or die ("MySQL error with query ( $sql ): ".mysql_error());
You MUST escape user input before using it in a query - you don't want a visit from Bobby Tables...
In the second query just use
insert into tbl_ms(m_name, ng_ID, status)
values ($app_id,last_insert_id() ,1)
no need to play this via PHP!
Make a variable $insertedID = mysql_insert_id(); just before the second $sql variable !
And in the second $sql query replace the $result with $insertedID
It should solve your problem !

Categories