I am trying to export a full table into SQL using data from an HTML table. I know how to export one row, but can't understand how to export multiple rows. Any advice?
<?php while ($row = $result->fetch_assoc()) :?>
<tr>
<form action="insertorder.php" method="post">
<td name="Item_ID[]"><?=$row["item_id"]?></td>
<td name="name[]"><?=$row["ITEM_NAME"]?></td>
<td name="suggested_qty"><?=$row["suggested_qty"]?></td>
<td name="price" class="pricetd"><?=$row["Price_item"]?></td>
<td>
<input type="text" name="editedvalues[]" class="qtyinput" value="<?=$row["suggested_qty"]?>" />
</td>
<td><input name='result[]' class="resultinput" /></td>
</tr>
<?php endwhile?>
<input type="submit" class="btn btn-dark" value="Submit">
</table>
</form>
Export script:
$sql = "INSERT INTO ms_order VALUES (item_id, item_name, order_quantity, total)";
for ($i=0; $i<count($_POST['Item_ID']); $i++) {
$sql .= '(\'' . $_POST['Item_ID'][$i] . '\', \'' . $_POST['name'][$i] . '\', \'' . $_POST['editedvalues'][$i] . '\', \'' . $_POST['result'][$i] . '\')';
if ($i<count($_POST['Item_ID']) - 1) {
$sql .= ',';
}
echo $sql;
}
The problem on your code it's that you're creating a new form for each fetched row on the while loop. By doing this, you're sending only one row whenever the form is submitted. To solve this you should place the form tag outside the while loop. Also, let me share with you a cleaner way to accomplish what you're doing:
$sql = "INSERT INTO ms_order (item_id, item_name, order_quantity, total) VALUES ";
$sql .= implode(',', array_map(function($item_id, $name, $editedvalues, $result) {
return <<<SQL
({$item_id}, {$name}, {$editedvalues}, {$result})
SQL;
}, $_POST['Item_ID'], $_POST['name'], $_POST['editedvalues'], $_POST['result']));
This is what it does:
array_map function fetchs each index of a given array, you can pass as an argument as many arrays as you wish, it will iterate over each index so you will be able to use each value to manipulate it and return it.
Each iteration of the array_map will create a new array, so in the end what you get is an array of arrays containing the returned results. Finally, as you want to make a multiple INSERT, you concatenate each array with a colon using the implode function.
Note that you should sanitize the $_POST values as you might be vulnerable to SQL Injection and other security issues. For further information about it, check it out here.
Greetings,
Matt
Related
As a new programmer I'm having trouble figuring out how to exactly code this situation. I've taken some of the solutions via stackoverflow but this one doesn't seem to work as I thought it would. I have a tag that correctly puts in one selected item but if I put in two or three it gives me the numbers. I.e. if I selected 3 options with id's 3, 5 and 8 it turns into 358 instead of creating a many-to-many catalog relationship of 3-3, 3-5, 3-8.
The purpose is that the form is creating a new character that can gain several disadvantages. These disadvantages are then linked to the new characters unique id.
$query2 = implode ( "",$_POST['did']);
$sql="INSERT INTO player_disadvantage
(disadvantageid,characterid)
VALUES ('".$query2."',LAST_INSERT_ID())"
;
<tr>
<td>Disadvantages</td>
<td>
<?php
$result = $mysqli->query("SELECT * FROM disadvantages");
echo '<SELECT multiple="multiple" id="did" name="did[]">';
while($row1 = $result->fetch_assoc()) {
$disadvantages = $row1['name'];
$disadvantagesid = $row1['did'];
$disadvantagescost = $row1['cost'];
echo "<option value='".$disadvantagesid."'>". '+' . ' ' . $disadvantagescost . ' ' . $disadvantages . "</option>";
}
echo '</select>';
?>
</td>
My only guess is to find a way to move the code so that it puts the LAST_INSERT_ID() with every disadvantage id. I'm not sure how to code it.
Try this:
$values = implode(',', array_map(function($x) {
return "('" . mysql_real_escape_string($x) . "', LAST_INSERT_ID())"; },
$_POST['did']));
$sql = "INSERT INTO player_disadvantage (disadvantageid, characterid) VALUES $values";
This creates a query that looks like:
INSERT INTO player_disadvantage (disadvantageid, characterid)
VALUES ('3', LAST_INSERT_ID()),
('5', LAST_INSERT_ID()),
('8', LAST_INSERT_ID())
to add multiple rows.
I'm trying to achieve a multiple update in one submit. I have a table with a number of rows and want to be able to update one field in each row just by tabbing to the next insert box.
My code is thus:-
//start a table
echo '
';
//start header of table
echo '<tr>
<td width="60" align="center"><strong>Lab Item ID</strong></td>
<td width="60" align="center"><strong>Test Suite Name</strong></td>
<td width="60" align="center"><strong>Test Name</strong></td>
<td width="50" align="center"><strong>Result</strong></td>
</tr>';
//loop through all results
while ($row=mysql_fetch_object($sql)) {
//print out table contents and add id into an array and email into an array
echo '<tr>
<td align="center"><input name="id[]" value='.$row->lab_item_id.' readonly> </td>
<td align="center">'.$row->test_suite_name.'</td>
<td align="center">'.$row->test_name.'</td>
<td><input name="test_result[]" type="text" value="'.$row->test_result.'"></td>
</tr>';
}
//submit the form
echo'<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>';
//if form has been pressed proccess it
if($_POST["Submit"])
{
//get data from form
//$name = $_POST['name'];
//$_POST['check_number'] and $_POST['check_date'] are parallel arrays
foreach( $_POST['id'] as $id ) {
$tresult = trim($_POST['test_result']);
$query = "UPDATE tbl_lab_item SET test_result='$tresult' WHERE lab_item_id = '$id'";
//execute query
}
print_r($_POST);
var_dump($tresult);
//redirect user
$_SESSION['success'] = 'Updated';
//header("location:index.php");
}
?>
When I print the $_POST arrays, everything is populating fine, however the variable is Null. I know I can't do a foreach on multiple arrays (at least I don't think I can) so is there some other trick I'm missing please? I can't be far away as the $_Post print has the right data in it.
Incidentally, the whole thing is generated by a query, so I never know how many records I'll have to update.
I've been looking at this (and other) forums, but can't seem to get a solution. I thought I understood arrays, but now I'm beginning to wonder!
edit - it's the $tresult variable that isn't working.
Many thanks,
Jason
Edit Thursday 21st Feb (05:41 UK time)
Thanks for your input everybody. I've solved this one now, and your collective advice helped. The code that finally cracked it is:-
//get data from form
$id1 = $_POST['id'];
$test_result1 = $_POST['test_result'];
foreach ($id1 as $key => $value){
$query = "UPDATE tbl_lab_item SET test_result='$test_result1[$key]' WHERE lab_item_id=$value ";
//execute query
Working through which variables etc were populated and what they were populated with was the key. Back to first principles, isn't it?
Cheers all.
J
Actually, you might get it done by doing a simpler (basic) form of for loop:
//get data from form
//$name = $_POST['name'];
//$_POST['check_number'] and $_POST['check_date'] are parallel arrays
$numberOfData = count($_POST['id']);
for($index = 0; $index < $numberOfData; $index++)
{
$id = $_POST['id'][$index];
$tresult = trim($_POST['test_result'][$index]);
$query = "UPDATE tbl_lab_item SET test_result='$tresult' WHERE lab_item_id = '$id'";
//execute query
}
print_r($_POST);
I hope this helps.
Cheers
change the query like this :
$query = "UPDATE tbl_lab_item SET test_result=$tresult WHERE lab_item_id = $id";
By adding single quotes ' ' you tell it to read is as a String and not to take the value of the var.
Edit
Replace your foreach loop with the following and let me know :
$id1 = $_POST['id'];
$test_result1 = $_POST['test_result'];
foreach( $id1 as $key => $value ) {
$query = "UPDATE tbl_lab_item SET test_result='$test_result1[$key]' WHERE lab_item_id = '$key' ";
}
Problem is that you're telling PHP to build your input fields as arrays, but then treat it as a string later:
<td><input name="test_result[]" type="text" value="'.$row->test_result.'"></td>
^^--- array
$tresult = trim($_POST['test_result']);
^^^^^^^^^^^^^^^^^^^^^--- no array key, so you're assigning the entire array
$query = "UPDATE tbl_lab_item SET test_result='$tresult'
^^^^^^^^^^--- array in string context
trim() expects a string, but you pass in an array, so you get back a PHP NULL and a warning. That null then gets stuffed into your SQL statement, and there's your problem.
I have a HTML form; I want to be able to set it so that if a field is empty, the field in the DB will actually be NULL and not just have the word NULL in the field. I thought that using this code would help, but it just puts the word NULL in the field.
PHP Code:
<pre>
<?php
if (isset($_POST['oc_item'])) {
$oc_item = mysql_escape_string($_POST['oc_item']);
$oc_itemdesc = (!empty($_POST['oc_itemdesc'])) ? $_POST['oc_itemdesc'] : NULL;
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES(''$oc_item','$oc_itemdesc')";
mysql_query($SQL);
if (mysql_query($sql)) {
echo '<strong><em>Your data has been submitted</em></strong><br /><br />';
} else {
echo '<p>Error adding submitted info: ' . mysql_error(). '</p>';
}
}
?></pre>
HTML Code:
<pre>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td>Item Name</td>
<td><input class="forms" type="text" size="50" maxlength="50" name="oc_item" /></td>
</tr>
<tr>
<td>Item Description</td>
<td><input class="forms" type="text" size="50" maxlength="50" name="oc_itemdesc" /></td>
</tr>
</table>
<p><input type="submit" value="Submit item" /></p>
</form></pre>
I want the field to actually be NULL and not have the field contain the word NULL. Thanks in advance.
If you want to write NULL to a MySQL database, you really have to put NULL there without quotation marks.
Like this:
INSERT INTO table (column, column2) VALUES ('mystring', NULL);
It’s always a bit effort if you want to do this manually by hand, because you would have to make if-conditions for the query.
Remember: PHP null != MySQL NULL. They both do not know each other at all.
But I am still wondering, what does that all have to do with the question name? (SELECT unless)
You could write your code like this:
$oc_item = mysql_escape_string($_POST['oc_item']);
$oc_itemdesc = (isset($_POST['oc_itemdesc']) && trim($_POST['oc_itemdesc']) != '') ? "'" . mysql_escape_string($_POST['oc_itemdesc']) . "'" : 'NULL';
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('" . $oc_item . "', " . $oc_itemdesc . ")";
# sorry for adding " . all the time, but I dislike variables within strings :D
But I have to admit I do not like that much either, as it moves the duty to wrap quotation marks around MySQL strings away from the SQL-query itself.
If you printed out $sql, you'd see that it's inserting , 'NULL'.
You need to modify your code so that it inserts the work "NULL" (without '' quotes) or, better, doesn't insert that parameter at all (eliminate the entire , 'NULL' part of the string.
Try this:
$oc_itemdesc = (!empty($_POST['oc_itemdesc'])) ? "'".$_POST['oc_itemdesc']."'" : "NULL";
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('$oc_item',$oc_itemdesc)";
As it stands you are adding 'NULL' instead of NULL so it is adding the words instead of the value.
Side Note: I would be careful and properly escape/encode the $_POST['oc_itemdesc'] as someone who put an apostrophe in the description would completely throw off the insert statement. For example: I don't like this would look like this:
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('$oc_item','I don't like this')";//MYSQL Error
PPS: As it stands you are inserting TWICE:
mysql_query($SQL);//insert 1
if (mysql_query($sql)) {//insert 2
The function that I use for the MySQL data from the HTML forms.
function emptyHtmlFormToNull($arr){
foreach($arr as $key => $val){
if(empty($val) || strtolower($val) === 'null'){
$arr[$key] = null;
}
}
return $arr;
}
I have a form that searches a MySQL database using PHP. Currently, when a user inputs a search into one of two fields, the entire contents of the database are displayed. Also, if the user leaves both fields blank, again, the entire contents of the database will be displayed.
However, if the user inputs random information into both of the fields, then the results page will be blank.
The assumed usage of this form is that the user can search for an article based on the article's title, the article's author or organization, or the article's title and its author or organization by either filling out one or both of the fields.
What I'm trying to figure out is:
Why the results page keeps displaying all of the database contents.
and
How to ensure that the database is actually being queried rather than just being dumped by a coding error.
Code follows below:
search.php:
<div class="content">
<form id="form1" name="form1" method="post" action="searchdb.php">
<table width="100%" border="0" cellpadding="6">
<tr>
<td width="29%" align="right">Article Title:</td>
<td width="71%" align="left"><input name="articletitle" type="text" id="articletitle" size="50" /></td>
</tr>
<tr>
<td align="right">Author or Organization:</td>
<td align="left"><input name="articleorganization" type="text" id="articleorganization" size="50" /></td>
</tr>
</table>
<table width="100%" border="0" cellpadding="6">
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</form>
</div>
searchdb.php
<?php
include('settings.php');
$query = "select * from articles";
$where = array();
if (!empty($_POST['articletitle'])) {
$where[] = "articletitle LIKE '%".mysql_real_escape_string($_POST['articletitle'])."%'";
}
if (!empty($_POST['articleorganization'])) {
$where[] = "articleorganization LIKE '%".mysql_real_escape_string($_POST['articleorganization'])."%'";
}
if (!empty($where)) {
$query .= " WHERE " . implode(" OR ", $where);
$sql = mysql_query($query);
} else {
// No results
}
while ($row = mysql_fetch_array($sql)){
echo '<br/> Article Title: '.$row['articletitle'];
echo '<br/> Article Organization: '.$row['articleorganization'];
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo '<td>View Full Entry</td>';
echo '<br/><br/>';
}
?>
When both are blank, your query states:
WHERE field LIKE '%%'
which matches everything.
The same happens when either one is blank, because you are using an OR to join the where clauses.
You can prevent this from happening, by checking the inputs aren't blank:
<?php
if (!((empty($_POST['field1']) || empty($_POST['field2']))) {
//run your query
}
Following on the post by #sberry.
if (isset($_POST['articletitle']) && $_POST['articletitle'] != "")
The variable can be set, but still be an empty string.
The method used by #xbonez is simpler as
if (!empty($_POST['articletitle'])) is the same as the above example that requires two tests
Have you tried xbonez method?
To be complete, this checks that at least one of the fields has been filled in:
if (!empty($_POST['articletitle']) || !empty($_POST['articleorganization'])) {
$query = "SELECT * from `articles` WHERE ";
$query .= "`articletitle` LIKE '%" . mysql_real_escape_string($_POST['articletitle']) . "%' ";
$query .= "OR `articleorganization` LIKE '%" . mysql_real_escape_string($_POST['articleorganization']) . "%'";
$sql = mysql_query($query);
} else {
// No results
}
Things that will only be used if one of the fields is filled in like:
$query = "SELECT * from `articles` WHERE ";
are placed inside the the if() statement, otherwise they are being parsed unneccesarily.
No need to create an array and then convert it into a string. ".=" will concatenate the string fragments into the final query string.
Matters of personal preference:
MySql keywords written in full caps, I find it makes the statements easier to read.
There are numerous discussions about it.
Search for "sql uppercase keywords style"
Using backticks around table and fieldnames:
Allows the use of reserved keywords for table or fieldnames (count, case, default, div, index, key, limit, option, order, etc...).
Reduces work for the mysql parser, it doesn't need to check whether there is a reserved word conflict.
Avoids problems if your table or field name becomes a reserved keyword in the future.
Again, numerous discussions. Search for "mysql backtick"
MySQLdocumentation:
9.3. Reserved Words
9.2. Schema Object Names
Look for "quoted identifier" on this page.
Also, if you might be migrating to a different database app in the future , you could use double quotes instead of backticks, look for "ANSI_QUOTES".
9.2.4. Function Name Parsing and Resolution
Look for "quoted identifier" on this page.
Tested this, and it should do exactly what you want.
$query = "select * from articles";
$where = array();
if (!empty($_POST['articletitle'])) {
$where[] = "articletitle LIKE '%".mysql_real_escape_string($_POST['articletitle'])."%'";
}
if (!empty($_POST['articleorganization'])) {
$where[] = "articleorganization LIKE '%".mysql_real_escape_string($_POST['articleorganization'])."%'";
}
if (!empty($where)) {
$query .= " WHERE " . implode(" OR ", $where);
$sql = mysql_query($query);
} else {
// No results
}
EDIT
It appears your form is passing empty values, so instead of checking isset, check !empty. I have updated the code above.
I have been struggling through PHP and sqlite for a bit now and I'm just confusing myself.
I have an html form that accessess a php script called processFeedback.php.My html code looks like this..
<html>
<head>
</head>
<body>
<form action="processFeedback.php" method="POST">
<table>
<tr>
<td>Name:</td><td><input name="name"/></td>
</tr>
<tr>
<td>Email:</td><td><input name="email"/></td>
</tr>
<tr>
<td>Comments:</td><td><textarea name="comments"></textarea></td>
</tr>
<tr>
<td></td><td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>
and my php file looks like this...
<?php
try
{
//open the database
$db = new PDO('sqlite:feedback.db');
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["comments"];
//Insert record
$db->exec("INSERT INTO feedback (name, email,comments) VALUES ('&name', '&email','&comments');");
//now output the data to a simple html table...
print "<table border=1>";
print "<tr><td>Id</td><td>Name</td><td>Email</td><td>Comments</td></tr>";
$result = $db->query('SELECT * FROM feedback');
foreach($result as $row)
{
print "<tr><td>".$row['feedbackid']."</td>";
print "<td>".$row['name']."</td>";
print "<td>".$row['email']."</td>";
print "<td>".$row['comments']."</td>";
}
print "</table>";
$db = NULL;
}
catch(PDOException $e)
{
print 'Exception : ' .$e->getMessage();
}
?>
And here is my table creation method...
CREATE TABLE feedback (feedbackid INTEGER PRIMARY KEY,name TEXT,email TEXT,comments TEXT);
The form is outputting the table headers and also a record that I manually entered using the Terminal but it won't insert a record in??? Can anyone see an easy mistake?
Disco
//Insert record
$db->exec("INSERT INTO feedback (name, email,comments)
VALUES ('&name', '&email','&comments');");
One obvious issue is that you're doing no error checking:
if (1!=$db->exec("INSERT...)) {
print "Error: " . implode('/',$db->errorInfo()) . "\n";
}
While I'm not overly familiar with PDO, I don't see how your placeholders are getting mapped to the corresponding PHP variables - which is probably the cause of the error:
$bound=array(
$_POST["name"], $_POST["email"], $_POST["comments"]
);
$stm=$db->prepare("INSERT INTO feedback (name, email,comments)
VALUES (?, ?,?));"
if (!$stm || !$stm->execute($bound)) {
print "Error: " . implode('/',$db->errorInfo()) . "<br />\n";
}
Check to make sure the PK column [feedbackid] is auto-generated in the database (AUTOINCREMENT).
EDIT: THis is not absolutely necessary but the lack of an explicit AUTOINCREMENT may be confusing the middleware. At least it cannot hurt to try adding an explicit AUTOINCREMENT to another table to test.
I had a similar problem in a PHP form where I used php to get data from a sqlite database and autofil fields.
You have
$db->exec("INSERT INTO feedback (name, email,comments) VALUES
('&name', '&email','&comments');");
I beleive that this should be
$db->exec("INSERT INTO feedback (name, email,comments) VALUES (" .
$name . "," . $email . "," . $comments . ");");
The period "." character combinds strings. Because you need exec() to basically be a one line sting (sql statement), you want to combine your written text with your variables as a string. I am not sure what the & does in place of the $ in a variable name in php, but I know in some functions the variable prefix is actually : instead of $ but the : variables have to be "bound" from a value.
see what does 'period' character do in php
I am by no means an expret but I happen to have the same problem as you so I hope I helped :)
EDIT: I just noticed this article is quite old. I hope this helps someone in the future with newer PHP.