Combining two PHP variables for MySQL query - php

I have a variable formvar that is incremented every time a user adds an additional field in an HTML form. This variable is posted to the PHP script for the purpose of looping through all of the added fields.
I am trying to combine two variables in the MySQL query to match what is in my HTML form. I would like the MySQL query to go upc0, upc1, etc until the for loop terminates.
for($i=0;$i<=$_POST[formvar];$i++)
{
mysql_select_db("bits", $con);
$sql="INSERT INTO report (UPC, Quantity, Comment)
VALUES ('$_POST[upc].$i','$_POST[quantity].$i','$_POST[comment].$i')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else echo "Records added successfully";
}
Sorry if this code is bad, I am new to web programming.
Thank you!

Ok, since each answer hinted at escaping (but did not give an example):
$sql = "INSERT INTO report (UPC, Quantity, Comment) VALUES
('" . mysql_real_escape_string($_POST["upc".$i]) . "','" .
mysql_real_escape_string($_POST["quantity" . $i]) . "','" .
mysql_real_escape_string($_POST["comment" . $i]) . "')";
That should protect you from SQL Injection, and is one proper method of creating sql queries. The best method would be to use parametrized queries (There's a ton of information out there on it, so I'd suggest a good Google search would be better than me trying to explain it here)...

First things first. In your HTML, create Input-Fields like this:
<input type="foo" name="upc[]">
<input type="foo" name="quantity[]">
<input type="foo" name="comment[]">
Then in your PHP-Script you do it like this:
<?php
# Choose DB
mysql_select_db("bits", $con);
# Iterates the Form-Data
$data_arr = array();
foreach($_POST['upc'] as $k=>$v) {
# Makes sure all needed data is available
if(isset($_POST['quantity'][$k], $_POST['comment'][$k])) {
$data_arr[] = array(
'upc' => $v,
'quantity' => $_POST['quantity'][$k],
'comment' => $_POST['comment'][$k]
);
}
}
# Build mysql insert string
foreach($data_arr as $k=>$v) {
# Escapes each field
$v = array_map('mysql_real_escape_string', $v);
# Maps array to value set
$data_arr[$k] = '('. implode(',', $v). ')';
}
$sql = 'INSERT INTO report (UPC, Quantity, Comment) VALUES '. implode(', ', $data_arr);
# Perform mysql query
mysql_query($sql, $con) or die('Error: ' . mysql_error());
echo 'Records added successfully';
Wrote it on my iPad, i'm on an airplane... so untestet. Good luck. ;o)

Not sure if I understand the question well but this is what I think :
$sql="INSERT INTO report (UPC, Quantity, Comment) VALUES
('" . $_POST["upc".$i] . "','" . $_POST["quantity" . $i] . "','" . $_POST["comment" . $i] . "')";
Note : this is a short version, you must add mysql_real_escape_string, etc, etc.
Also I supposed every variable could be string so I surrounded them by ''.
$_POST["name" . $i] let you loop throught POST variables starting with the name "name" followed by a number, this must be inserted into your for loop.

As recipes are so acclaimed I'm going to give my own, concerning the actual question:
<?php
for ($i=0; $i<=$_POST['formvar']; ++$i) {
mysql_select_db("bits", $con);
$v = array_map(mysql_real_escape_string(array(_POST["upc{$i}"], $_POST["quantity{$i}"], $_POST["comment{$i}"])));
$sql = "INSERT INTO report (UPC, Quantity, Comment) VALUES('"
. implode("', '", $v)
. "')";
if (!mysql_query($sql,$con)) {
trigger_error(html_entities('Error: ' . mysql_error()));
}
}
?>

Related

Double Passing Rows into MySQL Databases using PHP

eBay Platform Notifications recommends periodic polling of the GetOrders API to ensure each and every order is received.
In my case, I have Platform Notifications set-up to parse the XML file received and insert it into a MySQL database using PHP.
Now I am looking to, as recommended, "double pass" using GetOrders, which should essentially give me duplicates for each and every single row (or order).
My structure is rather straightforward. But I have a UNIQUE INDEX for OrderLineItemID which, to my understanding, is the unique identifier for each eBay Order.
Is there a better way to do this than I am currently doing?
//retrieve and escape variables for insertion//
$sql = "INSERT INTO eBayOrders (OrderLineItemID, SalesRecordNumber, BuyerUserID, BuyerEmail, Title, SKU, Quantity, TransactionPrice)
VALUES ('".$orderlineitemid."', '".$recordnumber."', '".$buyeruserid."', '".$buyeremail."', '".$title."', '".$sku."', '".$qty."', '".$transactionprice."')";
}
if ($connect->query($sql) === TRUE) {
echo "New Record Created Successfully";
} else {
echo "Error: " . $sql . "<br />" . $connect->error;
$connect->close();
die();
}
Because of my UNIQUE ON OrderLineItemID, when a duplicate order comes in, the query will result in an error, close the connection, and then exit the script.
I've thought about first checking to see (maybe using a SELECT statement) if the row exists, and then trying an insert, but I'm doing a foreach loop of up to 100 orders using the GetOrders API to run my SQL queries, and it seems like just allowing it to fall to error might be a quicker option, but I'm weary on if this can cause issues down the line.
In all, I'm not familiar with best practices for MySQL "double passes". Anyone have any insight on the best way to conduct this?
edit: here is my entire foreach loop:
foreach ($orders as $order) {
$i++;
$buyeruserid2 = $order->BuyerUserID;
$buyeruserid = mysqli_real_escape_string($connect, $buyeruserid2);
// $extendedorderid = $order->TransactionArray->Transaction->ExtendedOrderID;
$buyeremail2 = $order->TransactionArray->Transaction->Buyer->Email;
$buyeremail = mysqli_real_escape_string($connect, $buyeremail2);
$salesrecordnumber2 = $order->TransactionArray->Transaction->ShippingDetails->SellingManagerSalesRecordNumber;
$salesrecordnumber = mysqli_real_escape_string($connect, $salesrecordnumber2);
$orderlineitemid2 = $order->TransactionArray->Transaction->OrderLineItemID;
$orderlineitemid = mysqli_real_escape_string($connect, $orderlineitemid2);
$title2 = $order->TransactionArray->Transaction->Item->Title;
$title = mysqli_real_escape_string($connect, $title2);
$sku2 = $order->TransactionArray->Transaction->Item->SKU;
$sku = mysqli_real_escape_string($connect, $sku2);
$quantitypurchased2 = $order->TransactionArray->Transaction->QuantityPurchased;
$quantitypurchased = mysqli_real_escape_string($connect, $quantitypurchased2);
$transactionprice2 = $order->TransactionArray->Transaction->TransactionPrice;
$transactionprice = mysqli_real_escape_string($connect, $transactionprice2);
echo $i;
echo "\n";
echo "BuyerUserID: " . $buyeruserid . "\n";
echo "extendedorderid: " . $quantitypurchased . "\n";
echo "BuyerEmail: " . $buyeremail . "\n";
echo "SellingManagerSalesRecordNumber: " . $salesrecordnumber . "\n";
echo "OrderLineItemID: " . $orderlineitemid . "\n";
// echo "ExtendedOrderID: " . $transaction->ExtendedOrderID . "\n";
echo "Title: " . $title . "\n";
echo "SKU: " . $sku . "\n";
echo "QuantityPurchased: " . $quantitypurchased . "\n";
echo "TransactionPrice: " . $transactionprice . "\n";
echo "\n";
$sql = "INSERT INTO eBayOrders (OrderLineItemID, SalesRecordNumber, BuyerUserID, BuyerEmail, Title, SKU, Quantity, TransactionPrice)
VALUES ('".$orderlineitemid."', '".$recordnumber."', '".$buyeruserid."', '".$buyeremail."', '".$title."', '".$sku."', '".$qty."', '".$transactionprice."')";
if ($connect->query($sql) === TRUE) {
echo "New Record Created Successfully";
} else {
echo "Error: " . $sql . "<br />" . $connect->error;
$connect->close();
die();
}
}
To avoid an error when an INSERT fails due to a unique key constraint, we can use the IGNORE option on the INSERT statement.
INSERT IGNORE INTO eBayOrders ...
If you use the IGNORE modifier, errors that occur while executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row is discarded and no error occurs. Ignored errors generate warnings instead.
But this also affects error conditions other than duplicate key exceptions.
As another option, we can use INSERT ... ON DUPLICATE KEY ...
Documentation available here:
Reference: https://dev.mysql.com/doc/refman/5.7/en/insert.html

Inserting values from multiple checkboxes and textfields

I am a beginner in PHP.I am stuck with a problem. The idea is that I have to assign actors to a selected movie and add a role for each. I need to pick several values from the list and add a description for each via texfields. My code adds all the checked values to the database, but it makes a mess with the values from the textfields, the checked values don't match with the description. I would be really grateful for your help!
My code:
Form:
<?php
$sqlquery = "SELECT artistId, firstname, lastname from $artists order by 2";
$result = mysqli_query($connect, $sqlquery);
if($result) {
echo "<table class=\"addactor\">";
echo "<tr>
<td id=\"text\" colspan=\"2\"><h3>Assign an actor to the movie</h3></td>
</tr>";
while($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>";
echo "<input type=\"checkbox\" name=\"checkbox[]\" value=\"" . $sqlRow['artistId'] . "\"/> " . $sqlRow['firstname'] . " " . $sqlRow['lastname'] . "</td><td><input type=\"text\" name=\"textbox[]\"/></td>";
echo "</tr>";
}
echo "<tr><td align=\"right\"><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Add\"></td><td><input type=\"reset\" name=\"reset\" id=\"reset\" value=\"Reset\"></td></tr></table>;";
}
print '</table>';
The connection to the database is in another file, which is included here.
The second part:
if($_POST) {
$checkbox = $_POST['checkbox'];
$txt = $_POST['textbox'];
$len = sizeof($checkbox);
for($i = 0; $i < $len; $i++) {
$sqlqr = "INSERT INTO $role (artistId, movieCode, Description) VALUES ('" . $checkbox[$i] . "', '" . $_POST['moviecode'] . "', '" . $txt[$i] . "')";
mysqli_query($connect, $sqlqr);
}
$query = "INSERT INTO $movies(movieCode, title, dateOfIssue,category, description, image) VALUES ('" . $_POST['moviecode'] . "', '" . $_POST['title'] . "', '" . $_POST['dateofissue'] . "','" . $_POST['category'] . "', '" . $_POST['desc'] . "', '" . $_POST['image1'] . "')";
mysqli_query($connect, $query);
if(mysqli_query($connect, $query) || mysqli_query($connect, $sqlqr)) {
echo "<h4>1 record added</h4>";
}
else {
die('Error: ' . mysqli_error($connect));
}
print '</form>';
}
Unchecked values are not submitted and checkbox quantity not same with textbox.
You should give input name array same keys :
$i = 0;
while($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>";
echo "<input type=\"checkbox\" name=\"checkbox[".$i."]\" value=\"" . $sqlRow['artistId'] . "\"/> " . $sqlRow['firstname'] . " " . $sqlRow['lastname'] . "</td><td><input type=\"text\" name=\"textbox[".$i."]\"/></td>";
echo "</tr>";
$i++;
}
Use also this code:
$checkbox = $_POST['checkbox'];
$txt = $_POST['textbox'];
foreach ($checkbox as $key => $value)
$sqlqr = "INSERT INTO $role (artistId, movieCode, Description) VALUES ('" . $value . "', '" . $_POST['moviecode'] . "', '" . $txt[$key] . "')";
mysqli_query($connect, $sqlqr);
}
use mysql_escape_string($_POST['']) instead of the every field $_POST[''] in inside the mysqlquery.
As documented under 17.2.1 Control types:
When a form is submitted, only "on" checkbox controls can become successful.
In other words, the browser will only submit those checkbox controls that have been 'checked', yet will submit every textbox control irrespective of the status of the checkbox control with which you intended it to be associated.
Therefore, unless all checkbox controls were checked, the arrays $_POST['checkbox'] and $_POST['textbox'] created by PHP from the form submission will contain different numbers of elements—and, consequently, those with any given index may not match.
There are two ways of resolving this:
one can use client-side scripting to disable the textbox if the corresponding checkbox is unchecked: this will prevent the browser from submitting the textbox and, accordingly, the arrays in PHP will be aligned again (however note that this solution depends upon the availability of client-side script—you will have to test for and handle cases where such scripting is unavailable); or
one can give the controls explicit indexes to ensure that they are always aligned.
You also really ought to read up on proper string escaping (and how failure to do so exposes your application both to bugs and commonly exploited attack vectors): I thoroughly recommend #deceze's blog article, The Great Escapism (Or: What You Need To Know To Work With Text Within Text).
In particular, as he describes in his article, you should ensure that you escape any HTML in your variables before transmission to the browser (in order to prevent XSS attacks and bugs where the text to be output contains characters that have special meaning in HTML, for example <):
$result = mysqli_query($connect, "
SELECT artistId, CONCAT(firstname, ' ', lastname) AS fullname
FROM $artists
ORDER BY firstname
");
if ($result) {
echo '
<table class="addactor">
<tr>
<td id="text" colspan="2"><h3>Assign an actor to the movie</h3></td>
</tr>';
$i = 0;
while ($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo '
<tr>
<td>
<input type="checkbox"
name="checkbox[',$i,']"
value="', htmlentities($sqlRow['artistId']), '"
/>', htmlentities($sqlRow['fullname']), '
</td><td>
<input type="text" name="textbox[',$i,']"/>
</td>
</tr>';
$i++;
}
echo '
<tr>
<td align="right">
<input type="submit" name="submit" id="submit" value="Add">
</td><td>
<input type="reset" name="reset" id="reset" value="Reset">
</td>
</tr>
</table>';
}
Also, concatenating unescaped strings supplied by the user directly into your SQL not only makes you vulnerable to SQL injection attack, but furthermore introduces bugs where the strings contain characters that have special meaning within SQL string literals (for example ').
The solution is to prepare SQL statements with placeholders for parameters that get subsituted with your variables upon command execution; this also provides a performance boost since the statements need only be prepared once irrespective of the number of times that they are executed:
if ($_POST) {
$stmt = mysqli_prepare($connect, "
INSERT INTO $movies
(movieCode, title, dateOfIssue, category, description, image)
VALUES
(?, ?, ?, ?, ?, ?)
");
mysqli_stmt_bind_param($stmt, 'ssssss',
$_POST['moviecode'],
$_POST['title'],
$_POST['dateofissue'],
$_POST['category'],
$_POST['desc'],
$_POST['image1']
);
mysqli_execute($stmt) or die('Error: ' . mysqli_error($connect));
$stmt = mysqli_prepare($connect, "
INSERT INTO $role
(artistId, movieCode, Description)
VALUES
(?, ?, ?)
");
mysqli_stmt_bind_param($stmt, 'sss',
$checkbox,
$_POST['moviecode'],
$description
);
foreach ($_POST['checkbox'] as $i => $checkbox) {
$description = $_POST['textbox' ][$i];
mysqli_execute($stmt) or die('Error: ' . mysqli_error($connect));
}
echo '<h4>1 record added</h4></form>';
}

Calling user defined functions in php for mysql query

Hi I'm trying to call several functions that I have defined in php within mysql_query. The sql query executes successfully however all the columns which should contain values from functions are left empty in the database. The sql query looks like this:
$sqldescription = description($e->href);
$sqlimage = image($e->href,$e->innertext);
$sqlstatus = status($e->href);
$sqlgenre = genre($e->href);
$sqlauthor = author($e->href);
$sqlrelease = release($e->href);
$sql = "INSERT INTO manga (`manga_title`, `manga_description`, `manga_thumnail`, `manga_latest_chap`, `manga_status`, `manga_genre`, `manga_author`, `manga_released_date`, `manga_added_date`, `manga_link`) VALUES
('" . $e->innertext . "', '" . $sqldescription . "', '$sqlimage', '0', '$sqlstatus', '$sqlgenre', '$sqlauthor', '$sqlrelease', '" . date("Y-m-d") . "', '" . $e->href . "')";
mysql_query($sql,$con);
most of the functions are pretty similar and here is what one of them looks like:
function description($url){
$descriptionhtml = new simple_html_dom();
$descriptionhtml->load_file($url);
foreach ($descriptionhtml->find('p.summary') as $d)
echo $d;
}
I would appreciate any help :)

Insert Into Mysql DB

I am having a small issue with some coding of mine. For some reason my entries aren't dropping in my DB. Any suggestions would be greatly appreciated! Here is my code...
<?php
$dbhost="localhost";
$dbname="DBNAME";
$dbuser="USER";
$dbpasswd="PASSWORD"; // connect to the db
$dbcxn = mysqli_connect($dbhost, $dbuser, $dbpasswd);
if (!$dbcxn) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysqli_select_db($dbcxn, $dbname);
if (!$db_selected) {
die ('Can\'t use dbreviews : ' . mysql_error());
}
$query = "INSERT INTO entries ( submitterFirstName, submitterLastName, submitterPhone, submitterEmail, referredFirstName, referredLastName, referredPhone, referredEmail, referredReason)
VALUES ('$submitterFirstName', '$submitterLastName', '$submitterPhone', '$submitterEmail', '$referredFirstName', '$referredLastName', '$referredPhone', '$referredEmail', '$referredProject')";
$result=mysqli_query($dbcxn, $query);
?>
The first thing you want to check is echo the query back to yourself and read it over.
Second, check the table structure. Make sure the column names are all spelled correctly and that all fields exist in your table (I've accidently forgotten to add a column before).
Third, you may or may not receive error messages depending on your configuration. But, you can manually check.
if (!$result) {
echo mysqli_error($dbcxn);
}
First thing first should be code formatting, it will help you read the code and consequently find your errors easier.
$query = "
INSERT INTO
entries
(
submitterFirstName,
submitterLastName,
submitterPhone,
submitterEmail,
referredFirstName,
" .
"referredLastName,
referredPhone,
referredEmail,
referredReason
)
" .
" VALUES
(
'$submitterFirstName',
'$submitterLastName',
'$submitterPhone',
' $submitterEmail',
'$referredFirstName'," .
"'$referredLastName',
'$referredPhone',
'$referredEmail',
'$referredProject'
);
"
The above is your query string split onto several lines, there are some errors which should be evident straight away? Once formatted I would do echo $query and view the output of $query.
Also try seeing if you can do an insert without using php (using mysql workbench, php admin etc) then compare it with the string value you have set as $query.
// less errors, please note that inside "" you can include php $vars without needing to escape.
$query = "
INSERT INTO
entries
(
submitterFirstName,
submitterLastName,
submitterPhone,
submitterEmail,
referredFirstName,
referredLastName,
referredPhone,
referredEmail,
referredReason
)
VALUES
(
'$submitterFirstName',
'$submitterLastName',
'$submitterPhone',
'$submitterEmail',
'$referredFirstName',
'$referredLastName',
'$referredPhone',
'$referredEmail',
'$referredProject'
);
";
Change your query variable to:
$query = "INSERT INTO entries " .
"( submitterFirstName, submitterLastName, submitterPhone, submitterEmail, referredFirstName, " .
" referredLastName, referredPhone, referredEmail, referredReason )" .
" VALUES ('" .
$submitterFirstName . "', '" .
$submitterLastName . "', '" .
$submitterPhone . "', '" .
$submitterEmail . "', '" .
$referredFirstName . "', '" .
$referredLastName . "', '" .
$referredPhone . "', '" .
$referredEmail . "', '" .
$referredProject . "')";
and it should be working.
Suggesting to use mysqli prepare

Loop through form input array

I have a dynamic output form where the text input fields have the same name. I need to loop through
the text inputs and insert multiple rows into the database for each text field input.
$sql="INSERT INTO orderitems (orderNum,productNum,quant)
VALUES
('$num1','$_POST[pNum]','$_POST[quant]')";
<input type="text" name="pNum" value="<?php echo $t1; ?>"> //may have several with same name
If you want to submit your form with multiple inputs with the same name, you should add [] to the name. Then you can use it on PHP-side as every array (i.e. looping with foreach)
<input type="text" name="pNum[]" value="<?php echo addslashes($t1); ?>">
(by the way, remember always about quoting)
and on PHP side:
foreach($_POST['pNum'] as $value)
{
// remember about quoting here, too
}
Soooo.... loop through them and insert multiple rows?
for ($i = 0; $i < count($_POST['pNum']); $i++) {
$sql = 'INSERT INTO orderitems (orderNum, productNum, quant) VALUES ('
. "'" . mysql_real_escape_string($num1) . "', "
. "'" . mysql_real_escape_string($_POST['pNum'][$i]) . "', "
. "'" . mysql_real_escape_string($_POST['quant'][$i]) . "'"
. ')';
}
Note the use of mysql_real_escape_string. Never, NEVER, NEVER inject values from $_POST or $_GET or $_COOKIE or any other value your user has supplied directly into a SQL statement. Besides the potential to break if the value contains a ', this can also be used maliciously to inject SQL that alters (or erases) your database.
You can insert many rows with an INSERT request, you have just to create it with PHP
http://dev.mysql.com/doc/refman/5.0/en/insert.html

Categories