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');
Related
I am fairly inexperienced with php and sql and I am having an issue with php variables in the insert into SQL statement.
I have a SQL Table :
CREATE TABLE users (
userID INT PRIMARY KEY,
username VARCHAR(256),
password VARCHAR(256)
);
This isn't the way I made the table as it was made in phpmyadmin but that is exactly how it is
the PHP is so , there is validation code aswell but it is not necessary:
$userUsername = $_POST["username"];
$userPassword = $_POST["password"];
$sqlinsert = "INSERT INTO users(username,password) VALUES ('$userUsername','$userPassword');";
$insertquery = mysqli_query($conn,$sqlinsert)
or die ("Problem with insert query");
Either you need to assign auto increment to primary key (userID).
Or you have to pass value for it like
$sqlinsert = "INSERT INTO users(userID, username, password) VALUES (1, '$userUsername', '$userPassword');";
if you have Auto Increment in ID then leave a blank first
$sqlinsert = "INSERT INTO users(userID,username,password)
VALUES ('','$userUsername','$userPassword')";
Or fill it with ID if not Auto Increment.
$sqlinsert = "INSERT INTO users(userID,username,password)
VALUES ('1','$userUsername','$userPassword')";
And as already mentioned in comments of your post your code is vulnerable to SQL Injection.
can use PDO Prepare Statement,too not necessarily ofcourse
<?php
$fname= $_REQUEST['firstname'];
$lname= $_REQUEST['lastname'];
$email= $_REQUEST['email'];
$pass = $_REQUEST['password'];
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect ');
}
$ins1 = "INSERT into signup values( '$fname' , '$lname', '$email','$pass')";
$select = mysql_select_db('ait', $conn);
if(! $select)
{
die("<h2> incorrect input <h2>".mysql_error());
header('location:index.php');
}
$in1 = mysql_query($ins1);
if (!$in1)
{
die("<h2> incorrect input <h2>".mysql_error());
header('location:signed.php');
}
mysql_close($conn);
header('location:signed.php');
exit;
?>
I am making a sign up form and adding this in the database but I am getting this error "incorrect input Column count doesn't match value count at row 1". I am not inserting id from this code as it is auto increment.
Write down the names of columns explicitly in the query.
INSERT into signup(first_name,last_name,email,password)
values( '$fname' , '$lname', '$email','$pass')
Took at look at SQL injection. Passing parameters like this is not a safe approach.
If id is autoincrement (and it is the only column you skip and the first one in the table), use:
$sql = "INSERT into signup values (null, '$fname' , '$lname', '$email','$pass')";
This way, you let mysql fill in the id value, but you still need to specify it.
An alternative is to use:
$sql = "INSERT into signup (col1, col2, col3, col4) values ('$fname' , '$lname', '$email','$pass')";
Where you replace col* with the actual column names.
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')");
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');");
Is this possible if I want to insert some data into two tables simultaneously?
But at table2 I'm just insert selected item, not like table1 which insert all data.
This the separate query:
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
Can I insert COUNT(model) at table2?
I have found some script, could I use this?
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$result = mysql_query($sql,$conn);
if(isset($model))
{
$model = mysql_insert_id($conn);
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
$result = mysql_query($sql,$conn);
}
mysql_free_result($result);
The simple answer is no - there is no way to insert data into two tables in one command. Pretty sure your second chuck of script is not what you are looking for.
Generally problems like this are solved by ONE of these methods depending on your exact need:
Creating a view to represent the second table
Creating a trigger to do the insert into table2
Using transactions to ensure that either both inserts are successful or both are rolled back.
Create a stored procedure that does both inserts.
Hope this helps
//if you want to insert the same as first table
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (one,two, three) VVALUES('$one','$two','$three')";
$result = #mysql_query($qry2);
//or if you want to insert certain parts of table one
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (two) VALUES('$two')";
$result = #mysql_query($qry2);
//i know it looks too good to be right, but it works and you can keep adding query's just change the
"$qry"-number and number in #mysql_query($qry"")
its cant be done in one statment,
if the tables is create by innodb engine , you can use transaction to sure that the data insert to 2 tables
<?php
if(isset($_POST['register'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$website = $_POST['website'];
if($username == NULL OR $password == NULL OR $email == NULL OR $website == NULL) {
$final_report2.= "ALERT - Please complete all fields!";
} else {
$create_chat_user = mysql_query("INSERT INTO `chat_members` (`id` , `name` , `pass`) VALUES('' , '$username' , '$password')");
$create_member = mysql_query("INSERT INTO `members` (`id`,`username`, `password`, `email`, `website`) VALUES ('','$username','$password','$email','$website')");
$final_report2.="<meta http-equiv='Refresh' content='0; URL=login.php'>";
}
}
?>
you can use something like this. it works.
In general, here's how you post data from one form into two tables:
<?php
$dbhost="server_name";
$dbuser="database_user_name";
$dbpass="database_password";
$dbname="database_name";
$con=mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to the database:' . mysql_error());
$mysql_select_db($dbname, $con);
$sql="INSERT INTO table1 (table1id, columnA, columnB)
VALUES (' ', '$_POST[columnA value]','$_POST[columnB value]')";
mysql_query($sql);
$lastid=mysql_insert_id();
$sql2=INSERT INTO table2 (table1id, table2id, columnA, columnB)
VALUES ($lastid, ' ', '$_POST[columnA value]','$_POST[columnB value]')";
//tableid1 & tableid2 are auto-incrementing primary keys
mysql_query($sql2);
mysql_close($con);
?>
//this example shows how to insert data from a form into multiples tables, I have not shown any security measures