Related
I try to insert some values from a form into my database with this code:
<?php
$link = mysqli_connect("myHost", "myUsername", "myPW", "myDB");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$name1 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn1']);
$name2 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn2']);
$name3 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn3']);
$name4 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn4']);
$name5 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn5']);
$name6 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn6']);
// attempt insert query execution
$sql = "INSERT INTO anmeldungen (FR_PM) VALUES ('$name1')";
$sql = "INSERT INTO anmeldungen (SA_AM) VALUES ('$name2')";
$sql = "INSERT INTO anmeldungen (SA_PM) VALUES ('$name3')";
$sql = "INSERT INTO anmeldungen (SO_AM) VALUES ('$name4')";
$sql = "INSERT INTO anmeldungen (SO_PM) VALUES ('$name5')";
$sql = "INSERT INTO anmeldungen (MO_AM) VALUES ('$name6')";
if(mysqli_query($link, $sql)){
echo "Name ", $name1, " erfolgreich eingetragen. Wir freuen uns auf dich!";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
When I submit the form, it's creating a new row, but it's not inserting any values in all of the columns, but the column MO_AM. Is there a fault in my PHP?
Your query should look like:
$sql = "INSERT INTO anmeldungen
(FR_PM,SA_AM,SA_PM,SO_AM,SO_PM,MO_AM)
VALUES ('$name1','$name2','$name3','$name3','$name4','$name5','$name6')";
Are you sure that the $name variables have values?
Your SQL Query should be:
$sql = "INSERT INTO `anmeldungen`(`FR_PM`,`SA_AM`,`SA_PM`,`SO_AM`,`SO_PM`,`MO_AM`)
VALUES ('$name1','$name2','$name3','$name4','$name5','$name6')";
Though you shouldn't be using $variable as the insert you should look to binding these to prevent SQL Injections.
What you did just overwrite the query.You can insert multiple values into the same table.
Change your query:-
EDIT:
If you use multiple lines for the query it should look like this.
Also When you append the variable.
$sql = 'INSERT INTO anmeldungen (FR_PM,SA_AM,SA_PM,...)'
.' VALUES ('.$name1.','.$name2.','. .... .)'
;
Here I am trying to get the inserted id from MySQL database in the table I have product_id. After insert I want to get the latest inserted product_id and store it in array ['newid'][]
The insert query is going on pretty good, but I am not able to get the product_id in to the array. when I print the array I am getting NULL value.
$link = mysqli_connect(db_host,db_user,db_password,db_name);
if (condition) {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category,product_publish_status) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category','$approve')";
} else {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category')";
}
if(mysqli_query($link, $sqlin)){
$newisid = mysqli_insert_id($link);
$_SESSION['newid'][] = $newisid;
How can I solve this?
php.net : $mysqli->insert_id
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
Try using mysql_insert_id() to get previously inserted id.
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);//previously insert id here.
} else {
//error
}
See this and this
EDIT
You can also use LAST_INSERT_ID() for this. Check official mysql doc
Try this:
$link = mysqli_connect(db_host,db_user,db_password,db_name);
if (condition) {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category,product_publish_status) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category','$approve')";
} else {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category')";
}
if($link->query($sqlin)){
$newisid = $link->insert_id;
$_SESSION['newid'][] = $newisid;
}
Reference: http://php.net/manual/en/mysqli.insert-id.php
I would like to associate the image with firstname, lastname...how can I retrieve the last rowand use it to insert to the other table? I tried $image = $mysqli->insert_id; then binding but it doesn't work. Can someone help me out?
$image = $mysqli->insert_id;//this should come from table2
$stmt = $mysqli->prepare("
insert into table1 (username, firstname, lastname, image)
select ?,?,?,image from table2 t2 where username = ? and t2.id = ?
");
$stmt->bind_param('sssss', $username, $fname, $lname, $username, $image);
$stmt->execute();
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query, Example:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
output
New Record has id 1.
Reference
PHP mysqli_insert_id: http://www.php.net/manual/en/mysqli.insert-id.php
First of All you need to create auto_increment field in you ID
Then You can used
$last_id = mysqli_insert_id($conn);
after I get the last row from table2 I would like to insert it to table1. That is all I need
Go on:
insert into table 1 with simple regular insert query
get last insert id
insert into table 2 with simple regular insert query
As simple as that
I'm trying to POST to two tables at the same time. I'm trying to get the DonorID to display in to another table under $description. I'm able to just write any text in the $description, but I need it to be dynamic not static, which is what the text is. I have two tables; the first is accounting and the second is donations. I'm trying to alter the $description='Donation from Donor'; and have the donor that made the transaction be listed where the Donor is. Any suggestions would be greatly appreciated.
Here is my code:
<?php
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
$con = mysql_connect("$dbserver","$dblogin","$dbpassword");
if (!$con)
{
die('Could not connect to the mySQL server please contact technical support
with the following information: ' . mysql_error());
}
mysql_select_db("$dbname", $con);
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO accounting (date, transactiontype, account,
description, Income, Expense)
VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
mysql_query($sql2);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
header( 'Location: http://localhost/donations.php' ) ;
?>
As i said i would personaly use mysqli for new project, here a sample of you code with mysqli:
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
//opening connection
$mysqli = new mysqli($dbserver, $dblogin, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO `donations` (`date`, `firstname`, `middleinitial`, `lastname`, `organization`, `donorid`, `paymenttype`, `nonmon`, `Income`, `event`) Values ('$date','$firstname','$middleinitial','$lastname','$organization', '$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
$query1 = $mysqli->query($sql) or die($mysqli->error.__LINE__);
$query2 = $mysqli->query($sql2) or die($mysqli->error.__LINE__);
//closing connection
mysqli_close($mysqli);
header( 'Location: http://localhost/donations.php' ) ;
UPDATE
you can add donorid simply placing both vars in the query like:
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('".$date."','".$transactiontype."','".$account."','".$donorid . " " . $description."','".$Income."','".$Expense."')";
this way i just separate donorid and description with a space but you can add anything you want to in plain text:
'".$donorid . " - " . $description."'
After this
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
put
mysql_query($sql);
Please execute the query.
Things I see is ..
First your just executing your $sql2 but not the other $sql statement
Another is while inserting you declared some columns name that is a mysql reserved word (date column)
you should have `` backticks for them..
Refer to this link MYSQL RESEERVED WORDS
additional note: Your query is also vulnerable to sql injection
SQL INJECTION
How to prevent SQL injection in PHP?
Just write after insert on trigger on first table to insert data into another table.
You will have to split $sql2 to 2
1st :-
$sql2 = "INSERT INTO accounting (description) SELECT * FROM donations WHERE donorid='$donorid'"
then another one
"UPDATE accounting SET date='', transactiontype='', account ='', Income='', Expense ='' WHERE description=(SELECT * FROM donations WHERE donorid='$donorid')"
that will take all the information from donoation for the given donorid and list it under description in accounting
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 !