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 two tables
user_details
load_owner
user_details
user_id as primary key
name
password
phone
load_owner
load_owner_id as a primary key
user_id as foreign key
address
bank name
I need to insert all the values at the same time. I tried it but in load_owner table user_id values are insert as NULL. My PHP code is following
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$address = $_POST['address'];
$bank_name = $_POST['bank_name'];
$user_insert = mysql_query("insert into user_details (name, password, phone) values ('$name', '$password', '$phone')");
if($user_insert==false)
{
echo "".mysql_error();
}
$load_owner_insert = mysql_query("insert into load_owner ( address, bank_name) values ('$address''$bank_name')");
if($load_owner_insert==false)
{
echo "".mysql_error();
}
}
?>
That is because you aren't actually specifying user_id value while inserting to load_owner table. You need to fetch the user_id value first, so that it becomes:
$user_insert = mysql_query("insert into user_details (name, password, phone) values ('$name', '$password', '$phone')");
$user_id = mysql_insert_id();
And then insert user_id into load_owner
$load_owner_insert = mysql_query("insert into load_owner ( user_id, address, bank_name) values ($user_id, '$address', '$bank_name')");
PS: Use PDO with prepared statement, this SQL query is prone to SQL Injections and the mysql library is deprecated.
I'm new to PHP and so far I've managed to connect to my database, but when I try to send data to the database I don't get any script errors, but the data doesn't go through and I receive the message "Succesfully Created User!", which basically means the data has been sent right?
Here is my script:
<?php
$user = $_POST['user'];
$name = $_POST['name'];
$pass = $_POST['password'];
$con = mysql_connect("fdb13.awardspace.net", "myusername", "mypassword") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("myusername" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM unitytut WHERE `user`='".$user."'");
$numrows = mysql_num_rows($check);
if($numrows == 0)
{
$pass = md5($pass);
//$ins = "INSERT INTO unitytut (user, name, pass) VALUES ('John', 'Doe', 'John');";
//$ins = ("INSERT INTO `unitytut` (`user`), (`name`), (`pass`) VALUES ('' , 'John', 'Doe', 'John''John', 'Doe', 'John') ; ");
$ins = ("INSERT INTO `unitytut` (`user`), (`name`), (`pass`) VALUES ('' , '".$user."' , '".$name."', '".$pass."') ; ");
if($ins)
die("Succesfully Created User!");
else
die("ERROR");
}
else
{
die("user already exists!");
}
?>
I've tried several insert methods, but the only 3 functions that didn't receive the "ERROR" message was:
$ins = mysql_query("INSERT INTO unitytut (`user`), (`name`), (`pass`) VALUES ('' , '$user' , '$name', '$pass')" ) ;
and
$ins = ("INSERT INTO `unitytut` (`user`), (`name`), (`pass`) VALUES ('' , 'John', 'Doe', 'John''John', 'Doe', 'John') ; ");
and
$ins = ("INSERT INTO `unitytut` (`user`), (`name`), (`pass`) VALUES ('' , '".$user."' , '".$name."', '".$pass."') ; ");
I also have an ID in my table, but as I've been researching this issue without managing to fix it, I also read that I don't need to specify the ID in the script as the user is getting an ID automatically, but as I haven't gotten this to work I wouldn't know for sure.
I'm very new to php and databases in general, but I've been stuck on this for a while now, so any help would be greatly appreciated :)
Also any feedback on the way I posted this is also welcome, did I give you too much information, too many questions in one post, too much text etc.?
Thanks!
You should format your INSERT statement like this:
$ins = mysql_query("INSERT INTO unitytut (`user`,`name`,`pass`) VALUES ('$user' , '$name', '$pass')" ) ;
However, mysql_query is deprecated, See this link and follow it's advice on using a newer extension
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