PHP process page does not work - php

Hi guys my process page does not work, my code is
<?php
$id = $_POST['item_id'];
$qty = $_POST['item_qty'];
$name = $_POST['item_name'];
$con = mysqli_connect ("localhost", "name", "password", "db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO Temp (id, qty, name)
VALUES
('$_POST[id]', '$_POST[qty]', '$_POST[name]')";
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error());
}
header('Location: http://url.com/');
mysqli_close($con);
?>
Should be all correct, just copy from w3school,
The problem is, the db only get 0,
ie. my $id is 4, $qty is 12, $name is "Hello", after the process page, the table only get two 0s in id and qty, name is void.
The values should be processed to this process page successfully, bc I have tried
echo $id, $qty, $name;
All are the same as I typed in before.
Could anyone help me? thanks :-)

this line:
INSERT INTO Temp (id, qty, name) VALUES ('$_POST[id]', '$_POST[qty]', '$_POST[name]')";
should be:
INSERT INTO Temp (id, qty, name) VALUES ('$id', '$qty', '$name')";
If the form is from your previous question, you dont need:
$id = $_POST['item_id'];
$qty = $_POST['item_qty'];
$name = $_POST['item_name'];

I agree it looks like you left out item_. You might want to sanitize your data first.
$id=mysqli_real_escape_string($_POST['item_id']);
$qty=mysqli_real_escape_string($_POST['item_qty']);
$name=mysqli_real_escape_string($_POST['item_name']);
$sql = "INSERT INTO Temp (id, qty, name)
VALUES ('$id', '$qty', '$name')";

Related

php mysqli_multi_query() stops inserting after first query

I'm trying to insert multiple rows into the same table using a mysqli_multi_query function, but it only executes the first query. I have tried adding the values to the end of the first query separated by a comma as well, but nothing seems to work. Any suggestions?
I've switched to prepared statements but still only the first result is inserted. Am I missing something?
$DBConnect = mysqli_connect("localhost", "root", "", "getpressed");
if ($DBConnect->connect_error) {
die("Connection failed: " . $DBConnect->connect_error);
}
$stmt = $DBConnect->prepare("INSERT INTO orderdetails (orderID, productID, quantity) VALUES (?, ?, ?)");
$stmt->bind_param("iii", $orderID, $productID, $quantity);
$orderID = $orderID;
$productID = 1;
$quantity = $sportShirtQuantity;
$stmt->execute();
$orderID = $orderID;
$productID = 2;
$quantity = $sportCoatQuantity;
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$DBConnect->close();
I had a primary key index on orderID that wouldn't allow me to insert multiple rows with the same orderID. I'm an idiot. Thank you all for your help. It does work much better with prepared statements as suggested by tadman.
I changed your code a bit
$mysqli = new mysqli("localhost", "root", "", "getpressed");
if ($mysqli->connect_errno) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 1, '".$sportShirtQuantity."');";
$sql .= "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 2, '".$sportCoatQuantity."');";
if ($mysqli->multi_query($sql))) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
I also highly recommend you to use PDO prepared statements in future.
Remove the semicolon off of the last statement. The documentation notes that the semicolon for this method is used to concatenate statements, not end them.
Read the documentation here: Link
$sql = "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 1, '".$sportShirtQuantity."');";
$sql .= "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 2, '".$sportCoatQuantity."')";

How to get the last inserted id in PHP

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

How to insert data into MySQL using MySQLi?

I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.

php insert to sql not working

I'm on ubuntu running on apache2.
<?php
$con = mysqli_connect("localhost", "root", "password", "loops");
if (!mysqli_connect_errno()) {
echo "Error to connect: ".mysqli_connect_error();
}
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$age = $_POST['age'];
echo "First: ".$firstName."<br />Age: ".$age;
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values (".$firstName.",".$lastName.",".$age.")";
if (!mysqli_query($con)) {
die("Error :".mysqli_error($con);
}
echo "1 added";
mysqli_close($con);
?>
I don't know what to do now, but the error seems to be on the '$sql', 'cause when I put that
under a comment, the rest works...
You forgot the infamous mistake of wrapping the varchar variables with single quote '
"INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
Additionally, It's highly risky for you, not be using protections against SQL Injections
Try this, mysqli_query($con, $sql) You need to execute the query so that it will store into the database
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
if (!mysqli_query($con, $sql)) {
...................^
die("Error :".mysqli_error($con);
}
Try this:
$sql = "INSERT INTO persons (`FirstName`, `LastName`, `Age`) values (".$firstName.",".$lastName.",".$age.")";
If this doesn't work, what error do you get.

Php Post to two tables in Mysql

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

Categories