I have the following code, which will get values from these 9 variables and insert them in to a table. However, I don't know how to insert NULL value in to my table. As shown in line 10, if I try to use the keyword NULL, it consider as a string.
$WorkOrder = $_POST['WorkOrder'];
$Originated = $_POST['Originated'];
$CustID = $_POST['CustID'];
$Customer = $_POST['Customer'];
$Contact = $_POST['Contact'];
$Completed = $_POST['Completed'];
$AccountNum = $_POST['AccountNum'];
$Description = $_POST['Description'];
$Status = $_POST['Status'];
$Status = "NULL"; //Testing with NULL
$insertquery = "INSERT INTO ElectronicShop(WorkOrder, Originated, CustID, Customer, Contact, Completed, AccountNum, Description, Status)
VALUES ('$WorkOrder','$Originated','$CustID','$Customer','$Contact','$Completed','$AccountNum','$Description','$Status')";
$data = sqlsrv_query($connectString, $insertquery) or die(print_r(sqlsrv_errors(SQLSRV_ERR_ALL), true));
I will be getting values for these 9 variables via text boxes in a webpage. So, I can't manually enter NULL in my query.
Instead of:
$insertquery = "INSERT INTO ElectronicShop(WorkOrder, Originated, CustID, Customer, Contact, Completed, AccountNum, Description, Status) VALUES ('$WorkOrder','$Originated','$CustID','$Customer','$Contact','$Completed','$AccountNum','$Description','$Status')";
Use:
$insertquery = "INSERT INTO ElectronicShop(WorkOrder, Originated, CustID, Customer, Contact, Completed, AccountNum, Description, Status) VALUES
('$WorkOrder','$Originated','$CustID','$Customer','$Contact','$Completed','$AccountNum','$Description', NULL)";
You don't need to specify a variable for it, just write "NULL" without string marking signs (') into your query.
Greetz
Don't use the qoutes "":
$Status = "NULL";
Use:
$Status = null;
If you have not default value for Status column another than NULL, simply do not use this column in the columns list of insert statement.
Related
What I'm actually trying to do is insert a row with:
INSERT INTO users VALUES (col1, col2, ...)
where col1 is an auto_increment.
The PHP code is:
<?php
$host = "http://name.altervista.org/";
$user = "name";
$psw = "";
$db = "my_name";
$response = array();
$response["success"] = true;
$connessione = new mysqli($host, $user, $psw, $db);
if($connessione->connect_errno == 0)
{
$nome = $_POST["nome"];
$cognome = $_POST["cognome"];
$username = $_POST["username"];
$password = $_POST["password"];
$nTelefono = $_POST["nTelefono"];
$email = $_POST["email"];
$sql = "INSERT INTO users
VALUES (DEFAULT, '$nome', '$cognome', '$username', '$password', '$nTelefono', '$email')";
$ris = $connessione->query($sql);
if($connessione->affected_rows == 1)
{
echo(json_encode($response));
}
else
{
$response["success"] = false;
echo(json_encode($response));
}
}
else
{
$response["success"] = false;
echo(json_encode($response));
}
?>
I search similar questions here in stackoverflow, and I try to use DEFAULT or NULL, but it doesn't work. And if I put a number instead of the default value that is not already in the table it works, so I really don't understand where the problem is.
Have you any other suggestions?
EDIT: The table structure on the database:
click
EDIT 2: I tried to delete the table and create it again, and now it works with the NULL thing. Thanks for the support!
When you are doing an insert, list all the columns being inserted. You seem to want:
INSERT INTO users (nome, cognome, username, password, nTelefono, email)
VALUES ('$nome', '$cognome', '$username', '$password', '$nTelefono', '$email');
Next. Never store clear-text passwords in the database. You should be encrypting the value on the client side so the values are never passed over the network.
Next. Learn to use parameterized queries. When you munge query strings with parameter values, your are asking for inexplicable syntax errors and making the code subject to SQL injection attacks.
From the Mysql docs
INSERT INTO users VALUES ('$nome', '$cognome', '$username', '$password', '$nTelefono', '$email')";
The auto_increment fields doesn't need to be set in an INSERT statement
In MySQL, if you have an auto_increment column you don't need to put it in the insert statement.
Example:
You have the table:
CREATE TABLE test (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL
);
Your SQL statement should be:
INSERT INTO test(name) VALUES ('My name');
I have one field name is "owner". It is a foreign key Value. Initially i defined NULL value.
In PHP,
if($memberType=='owner'){
$ownerId = "";
}else{
$ownerId = $_POST['ownerId'];
}
$sql_user = mysqli_query($con,"INSERT INTO user(firstname, lastname,owner_id) VALUES ('$fname', '$lname', '$ownerId')");
Here Data is not inserting. When i remove owner_id during inserting, It is working.
How to define Null value to that
Your sql is fine. edit column in mysql, remove NOT NULL in the column.
$ownerId=0;
if($memberType=='owner'){
$ownerId = $_POST['ownerId'];
}
$sql_user = mysqli_query($con,"INSERT INTO user(firstname, lastname,owner_id) VALUES ('$fname', '$lname', '$ownerId')");
I'm trying to grab SID from the insert into the first table (stories) so I can insert that SID into the writing table in my second insert.
I think the way to do this is with mysql_insert_id(); after the first query, but the primary key that auto-increments is called SID. If mysql_insert_id() could grab that value I'd be all set.
What I am finding from a var_dump is that the $SID = mysql_insert_id(); is just returning the value "0" and I'm not sure why.
There is a column called ID in stores, but if it was grabbing that, the value would be "1". Either way, I wish this method could be written as mysql_insert_SID();
Any idea what I am doing wrong or how I can fix this? And yes, I know this is a deprecated approach, but first I want to figure out how before I worry about converting to PDO.
// Get values from form
$category = $_POST['category'];
$genre = $_POST['genre'];
$story_name = $_POST['story_name'];
$text = $_POST['text'];
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query);
$SID = mysql_insert_id();
$SID2 = "select stories.SID from stories where stories.SID=$SID";
$query2 = "INSERT INTO writing (ID, SID, text, position, approved)
VALUES('$user_ID', '$SID2', '$text', '1','N')";
$result = mysql_query($query2);
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
(http://php.net/manual/en/function.mysql-insert-id.php)
But you aren't executing any query (via mysql_query()). You're just assigning your query to a variable. Try following:
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
mysql_query($query);
$SID = mysql_insert_id();
I think you've forgotten to execute the query most probably?
Try
$SID = mysql_insert_id();
after executing the query
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query); // executing
$SID = mysql_insert_id(); // order of queries is important
If you cannot get the value through mysql_insert_id() then try SELECT LAST_INSERT_ID(). Of course there will be a value if you have executed an insert query with AUTOINCREMENT (which you haven't done yet)
I'm using mysqli in a PHP class.
I have this query to be executed:
INSERT INTO notifications (userid, content, uniq, link) VALUES (48, "[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9c602a02a26114a625", "http://website/somepost")
It fails, showing the error:
You have an error in your query etc. to use near '"[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9"'
But if I look in the DB, the new row is present.
The parameters are escaped using mysqli_real_escape_string():
$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);
$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ($userid, \"$msg\", \"$uniqid\", \"$link\")";
// die($sql);
$this->query($sql);
I tried to check query execution with $mysqli->affected_rows and !$result of mysqli_query().
The fields types are
INT (11) for userid,
TEXT for content,
TINYTEXT for uniq and
TINYTEXT for link.
All of the TEXT fields have collation "utf8_general_ci".
I didn't create the table.
The strange thing is that if I look in the database, the query was successfully executed...
Why is this happening?
you sql should be like
$userid = $this->escape($userid);
$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);
$link = $this->escape($link);
$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ('$userid', '$msg', '$uniqid', '$link')";
Great, now I can 'insert' into the database, but in phpmyadmin the fields are white, without content... This is the php code:
$name = $_POST["name"];
$institution = $_POST["institution"];
$email = $_POST["email"];
$country = $_POST["country"];
$hcp = $_POST["hcp"];
$texto = $_POST["texto"];
$state = $_POST["state"];
$license = $_POST["license"];
$consulta = ("INSERT INTO `1264`(`name`,`institution`,`email`,`country`,`hcp`,`texto`,`state`,`license`) VALUES ('$name','$institution','$email','$country','$hcp','$texto','$state','$license');");
mysql_query($consulta,$connection) or die("You cannot register. Try it later, please.");
Does anybody know why?
Please change your query
you have extra ',' both after 'license' and '$license'
$consulta = ("INSERT INTO `1264`(`id`,`name`,`institution`,`email`,`country`,`hcp`,`texto`,`state`,`license`) VALUES (NULL, '$name','$institution','$email','$country','$hcp','$texto','$state','$license');");
mysql_query($consulta,$connection) or die("You cannot register. Try it later, please.");
Also try using mysqli_* functions. mysql_* functions going to deprecated.
Try this:
$consulta = ("INSERT INTO `1264`(`id`,`name`,`institution`,`email`,`country`,`hcp`,`texto`,`state`,`license`) VALUES (NULL, '$institution','$email','$country','$hcp','$texto','$state','$license');");
ie, remove the extra comma at the last
Dont make the query so clumpsy. Here is a simple edit,
$consulta = "INSERT INTO `1264` SET
`name` = '$name',
`institution` = '$institution',
`email` = '$email',
`country` = '$country',
`hcp` = '$hcp',
`texto` = '$texto',
`state` = '$state',
`license` = '$license'";
You don't have to write the id and leave its value field null, it will be auto generated by default.
if id is an primary key then it should not be null
and if it is an auto increment field have no need to put it on field list and value
$consulta = ("INSERT INTO 1264(name,institution,email,country,hcp,texto,state,license,) VALUES ( '$name','$institution','$email','$country','$hcp','$texto','$state','$license',);");
do echo $consulta ;
to check if the query is coming properly or try put the variables out of cote check the name one
VALUES ( '".$name."','$institution','$email','$country','$hcp','$texto','$state','$license',)
This should work - enter each variable between quotes, especially when its a string
$consulta = ("INSERT INTO `1264`(`id`,`name`,`institution`,`email`,`country`,`hcp`,`texto`,`state`,`license`) VALUES (NULL, "'. $name ."','".$institution."','".$email."','".$country."','".$hcp.'","'.$texto.'","'.$state.'",'".$license."');");
Removed the last comma and Id -> NULL so try this:
`$consulta = ("INSERT INTO` `1264`(`name`,`institution`,`email`,`country`,`hcp`,`texto`,`state`,`license`) VALUES `('$name','$institution','$email','$country','$hcp','$texto','$state','$license');");