I have the following code that I created to update the database with the data coming from a a php form. $_POST['variables'] are different arrays.
the issue I am having is when I echo $updater the field status and the field display values are not in the correct order. for example if I check the checkbox 3. it will return the value enabled on the first line of the results. any suggestions would help thank you
//update data
$priority = $_POST['priority']; // this will be an array
$enable = $_POST['enable'];
$height = $_POST['height'];
$position = $_POST['position'];
$widgetid = $_POST['widgetid'];
$display = $_POST['display'];
$i = -1;
foreach($priority as $priori)
{
++$i;
$row_enable = $enable[$i];
$row_height = $height[$i];
$row_prio = $priority[$i];
$positio = $position[$i];
$disp = $display[$i];
$widgeti = $widgetid[$i];
if (isset($enable[$i]))
$enables ="y";
else
$enables ="n";
if (isset($display[$i]))
$displ = "y";
else
$displ = "n";
//DO THIS FOR THE REST AND THEN YOUR UPDATE QUERY
$updater = "UPDATE hpoptions SET position='$positio', height='$row_height', status='$enables', display='$displ', priority='$row_prio' WHERE userid='$ud' and widgetid='$widgeti'";
echo $updater."<br>";
} // ends here
There is no guarantee you will get your arrays in the desired order, unless you force it in the HTML. You probably have something like this:
<input type="text" name="position[]">
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w1">
...
<input type="text" name="position[]">
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w2">
...
You need to add an extra dimension to the arrays encoded on the field name. You need an unique id for each field group, and I believe your widgetid is exactly that, right? So you can do:
<input type="text" name="data[w1][position]">
<input type="text" name="data[w1][height]"> ...
...
<input type="text" name="data[w2][position]">
<input type="text" name="data[w2][height]"> ...
...
Notice you don't even need a field called widgetid anymore, since the ids will be encoded on every field name. In PHP, you do this to loop through the results:
foreach($_POST['data'] as $widgetid => $data) {
// Make sure to check if the values won't make your SQL query vulnerable to injection!
// http://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain
$widgetid = mysql_real_escape_string($widgetid);
$position = is_numeric($data['position']) ? $data['position'] : 0;
// ...
// Build your update query here
}
Related
basically i am trying to imput two arrays in the database but i can't seem to actually get them in the right tables.
here is the code for the php function:
$numecap1 = $_POST['numecap'];
$contentcap1 = $_POST['contentcap'];
$numecap = implode(" ", $numecap1);
$contentcap = implode(" ", $contentcap1);
$count_name = count($_POST['numecap']);
for($i=0;$i<$count_name ;$i++){
$_numecap = mysqli_escape_string($con,$numecap[$i]);
$_contentcap = mysqli_escape_string($con, $contentcap[$i]);
$sql3 = "INSERT INTO `".$prefix."".$titlu."`(numecap, contentcap) VALUES ('$numecap', '$contentcap')";}
and here is the html form (note: the java script adds how many text labales i need):
<form action="" method="post">
Nume table <input type="text" name="table"><br>
Autor <input type="text" name="autor"><br>
Nrcap <input type="text" name="cap"><br>
<input type="button" onclick="addInput()"/>
<span id="responce"></span>
<script>
var boxName2 = 0;
var boxName = 0;
function addInput()
{
var boxName="numecap";
document.getElementById('responce').innerHTML+='<br/>Nume cap<input type="text" name="'+boxName+'[]" " /><br/>';
var boxName2="contentcap";
document.getElementById('responce').innerHTML+='<br/>Continut cap<input type="text" name="'+boxName2+'[]" " /><br/>';
}
</script>
<input type="submit" name="SubmitButton"/>
</form>
If someone can help, itll be hghly appreciated, since i am desperate!
change your $sql to this:
$sql3 = "INSERT INTO `".$prefix."".$titlu."`(numecap, contentcap) VALUES ('$numecap[$i]', '$contentcap[$i]')";
because that way, you create a new row, insert only one value. create a new row, insert next value. And so on.
Your for loop should look like this:
for($i=0;$i<$count_name ;$i++){
$_numecap = mysqli_escape_string($con,$numecap[$i]);
$_contentcap = mysqli_escape_string($con, $contentcap[$i]);
$sql3 = "INSERT INTO `".$prefix."".$titlu."`(numecap, contentcap) VALUES ('$_numecap', '$_contentcap')";
mysqli_query($c, $sql3);
}
Perhpas you should look into the seralize and unseralize function which is available in PHP, this will assist you in inserting information into the database in the form of an Array!
$Array = array(1,2,3,4,5,6,7,8);
$Array_2 = array(1,43985);
$Array = seralize($Array);
$Array_2 = seralize($Array_2);
http://uk3.php.net/manual/en/function.serialize.php
http://uk3.php.net/manual/en/function.unserialize.php
I have several forms on a page called dispatch.php that each submit PHP code to INSERT into a database table and also UPDATE another database table. The main value that is INSERTED and UPDATED is the bolNum and containerNum.
Note: There can be more than 1 bolNum or containerNum at any time. You'll see the array and how I broke it down.
Here is 1 form (I shortened this as much as possible):
<form action="" method="POST"
id="serviceForm" name="serviceForm">
<label>Container Selected</label>
*** js populates bolNum & containerNum and displays it in these inputs ***
<input type="text" name="containerNum" id="containerNum" class="containerNum" />
<input type="text" name="bolNum" id="bolNum" class="bolNum" />
*** there are more form inputs, I just want to focus on the above 2 ***
<input type="submit" id="modal-form-submit" name="submit" value="Save" />
<?php
if(isset($_POST['submit'])){
$bolArray = explode(',', $_POST['bolNum']);
$containerArray = explode(',', $_POST['containerNum']);
$count = count($bolArray);
for($i = 0; $i < $count; $i++){
$bolService = $bolArray[$i];
$containerService = $containerArray[$i];
*** here is the first query ***
$sqlQuery = "INSERT INTO serviceTable (bol, container)
VALUES ('$bolService', '$containerService')";
*** here is the second query ***
$updateService = "UPDATE dispatchTable SET serviceColumn = 'Y'
WHERE CONTAINER_NUM = '$containerService' AND BOL_NUM = '$bolService'";
$updateServiceQuery = #mysql_query($updateService) or die ('error');
if(mysql_query($sqlQuery)){
$success = true;
}
else{
$success = false;
}
}
}
if($success){
echo "saved";
}
else{
echo "not saved";
}
?>
</form>
Here is another form. Basically, they are both the same, except for the names of the forms, and the names of the queries in the PHP.
<form class="well-small" action="" method="POST"
id="storageForm" name="storageForm">
<label>Container Selected</label>
*** js populates bolNum & containerNum and displays it in these inputs ***
<input type="text" name="containerNum" id="containerNum" class="containerNum" />
<input type="text" name="bolNum" id="bolNum" class="bolNum" />
*** there are more form inputs, I just want to focus on the above 2 ***
<input type="submit" id="modal-form-submit" name="submit" value="Save" />
<?php
if(isset($_POST['submit'])){
$bolArray = explode(',', $_POST['bolNum']);
$containerArray = explode(',', $_POST['containerNum']);
$count = count($bolArray);
for($i = 0; $i < $count; $i++){
$bolStorage = $bolArray[$i];
$containerStorage = $containerArray[$i];
*** here is the first query ***
$sqlQuery = "INSERT INTO storageTable (bol, container)
VALUES ('$bolStorage', '$containerStorage')";
*** here is the second query ***
$updateStorage = "UPDATE dispatchTable SET storageColumn = 'Y'
WHERE CONTAINER_NUM = '$containerStorage' AND BOL_NUM = '$bolStorage'";
$updateStorageQuery = #mysql_query($updateStorage) or die ('error');
if(mysql_query($sqlQuery)){
$success = true;
}
else{
$success = false;
}
}
}
if($success){
echo "saved";
}
else{
echo "not saved";
}
?>
</form>
If you'll notice the 2 queries per form, you will see the INSERT query updates to a different table. Whereas both forms have an UPDATE query that updates the same table, only different columns.
Again, I am having no problem with the INSERT queries. The problem lies with the UPDATE queries. Basically, if you complete the serviceForm, it should update the column in dispatchTable called serviceColumn, which it does. But it also updates the storageColumn which is also in dispatchTable. Vice versa for the completion of the storageForm.
When a form is complete, it should ONLY update the specified column for that form, not both columns for both forms.
I am not sure if it has something to do with the action of the forms being blank. Although I do believe the action may be the key to getting this to work correctly. I am not sure where to start.
Please advise.
* NOTE : I WILL BE USING PDO OR MYSQLI FOR THE NEXT APPLICATION *
Try to rename submit buttons in your forms:
....
<input type="submit" id="modal-form-submit" name="service_submit" value="Save" />
<?php
if(isset($_POST['service_submit'])){
....
and
....
<input type="submit" id="modal-form-submit" name="storage_submit" value="Save" />
<?php
if(isset($_POST['storage_submit'])){
....
Both fields are updated because both parts of PHP code are executed. The reason is you check the same post field $_POST['submit'] that is set when you submit any form on your page.
P.S.
Try to change your queries to make one query instead a lot of queries in a loop. Your application will work faster.
http://dev.mysql.com/doc/refman/5.0/en/update.html
http://dev.mysql.com/doc/refman/5.6/en/insert.html
Your code have one big hole named SQL injection. Try at least to escape values passed in query, even better use parameterized queries: http://php.net/manual/en/pdostatement.bindparam.php
I've a HTML form with approx. 120 input text fields.
Then i've a PHP page with the same form where i've this code to show the value get from database.
<input type="text" id="field_1" name="field_1" value="<?php echo $myvalue1; ?>" />
Is there a way to retrieve data from database and fill the input text value for each field or doing it in a better way than specify more than 120 variables?
Thanks!
There's a trick in PHP. You can name your inputs using "[]" operator. like this:
<input type="text" id="field_1" name="field[]" value="<?php echo $myvalue1; ?>" />
As the result it will be treated as an array in the corresponding REQUEST array (POST or GET, depends of HTTP method for you form).
To fill the inputs, simply use a loop.
You can always store the results in an array, then loop through that.
$q = mysql_query ( ... );
for ($i = 1; $r = mysql_fetch_row ($q); ++$i)
printf ('<input tyle="text" id="field_%s" name="field_%s" value="%s"/>', $i, $i, $r[0]);
Loop through your results from the query and generate textboxs
<?php
$sql = "SELECT column FROM table";
if ($result = $mysqli->query($sql)) {
while($obj = $result->fetch_object()){
echo "<input type='text' name='field[]' value='". $obj->column ."'> <br>"; // Here is the where you put your textbox in loop
}
}
$result->close();
?>
I am working on a car rental system, where the user can add a car into the php script which thereby adds the values into the back end dababase. I have a field called 'ID' which is auto incremented INT field. Everytime I add a car, the value is automatically added as an incremented Integer. Now, how I actually want it to be is different, for example if the name of the car to be added is 'MERCEDES', the ID value should be MER001. If the next car then added is VAUXHALL, the ID value should be VAU002 and so on. I know how to get 'MER' out of mercedes using the substring function in php, but I dont know how to have a loop counter and concatenate it with the extracted substring. I believe for this the ID field in my database table will have to be a VARCHAR but I dont know if a VARCHAR can be auto-incrementing (doesnt make sense). Here's the form to add the car.
Add a new Car to the database
Fill in the details below to Register
<label> Car Name
<span class="small">Enter car name</span>
</label>
<input type="text" name="CARNAME" id="CARNAME" />
<label>Fuel Type
<span class="small">Eg: Petrol</span>
</label>
<input type="text" name="FUELTYPE" id="FUELTYPE" />
<label>Transmission
<span class="small">Eg: Manuel</span>
</label>
<input type="text" name="TRANSMISSION" id="TRANSMISSION" />
<label>Engine Size
<span class="small">Eg: 2.4</span>
</label>
<input type="text" name="ENGINE_SIZE" id="ENGINE_SIZE" />
<label>Doors
<span class="small">Eg: 4</span>
</label>
<input type="text" name="DOORS" id="DOORS" />
<label>Total
<span class="small">Eg: 40</span>
</label>
<input type="text" name="TOTAL" id="TOTAL" />
<label>Available
<span class="small">Eg: 40</span>
</label>
<input type="text" name="AVAILABLE" id="AVAILABLE" />
<input type="submit" name="submit" value="Add Car">
<div class="spacer"></div>
</form>
This form takes you to adding.php which has the following code:
<?php
$link = mysql_connect ("xxxxx", "xxxxx", "xxxxx");
mysql_select_db ("xxxxx");
$ID = $_POST['ID'];
$CARNAME = $_POST['CARNAME'];
$FUELTYPE = $_POST['FUELTYPE'];
$TRANSMISSION = $_POST['TRANSMISSION'];
$ENGINE_SIZE = $_POST['ENGINE_SIZE'];
$DOORS = $_POST['DOORS'];
$TOTAL = $_POST['TOTAL'];
$AVAILABLE = $_POST['AVAILABLE'];
$DATEADDED = $_POST['DATEADDED'];
$test = substr($CARNAME,0,3); //tried to use this test variable and it works to get the substring!
if($TOTAL>=$AVAILABLE)
{
$query = "insert into car (ID,CARNAME,FUELTYPE,TRANSMISSION,ENGINE_SIZE,DOORS,TOTAL,AVAILABLE,DATEADDED) values ('$_POST[ID]','$_POST[CARNAME]','$_POST[FUELTYPE]','$_POST[TRANSMISSION]','$_POST[ENGINE_SIZE]','$_POST[DOORS]','$_POST[TOTAL]','$_POST[AVAILABLE]',CURDATE())";
$result = mysql_query($query);
header("location: list_logged.php");
}
else
{
echo "<script>alert('The Total number of cars cannot be less than Available number!'); location.href='add.php';</script>";
}
mysql_close ($link);
?>
Any suggestions as to how I can post something to ID to make it like MER001, MAC002...and so on? Right now it is just set to an auto incrementing value, which is added automatically. I know I'd have to change the field in the database from ID to VARCHAR but I dont know what to do next. I tried searching similar questions on substr and php counter concatenation but found nothing useful.
Spent some time and figured it out. You should really use PDO though. Also your database will look like this:
ID, CARNAME, FUELTYPE, TRANSMISSION, ENGINE_SIZE, DOORS, TOTAL, AVAILABLE, AND DATEADDED (WHICH IS A DATETIME DATA TYPE. THE REST ARE ALL VARCHARS).
One more thing. Instead of using CURDATE() you use NOW() which gives the date and time of insert into the db.
<?php
$link = mysql_connect ("***", "****", "*******");
mysql_select_db ("*****");
$CARNAME = $_POST['CARNAME'];
$FUELTYPE = $_POST['FUELTYPE'];
$TRANSMISSION = $_POST['TRANSMISSION'];
$ENGINE_SIZE = $_POST['ENGINE_SIZE'];
$DOORS = $_POST['DOORS'];
$TOTAL = $_POST['TOTAL'];
$AVAILABLE = $_POST['AVAILABLE'];
//FUNCTION TO GET LAST ID FROM DB
function getLastID(){ //Function to get last ID created and return
$query = "SELECT ID FROM car ORDER BY DATEADDED DESC LIMIT 1;";
$lastID = mysql_query($query);
$results = mysql_fetch_assoc($lastID);
return $results; //returns last id
}
//SWITCH CASE TO CREATE PREPENDING CARNAME
switch ($CARNAME) { //PreString based off of form input
case 'MERCEDES':
$preString = 'MER';
break;
case 'VAUXHALL':
$preString = 'VAU';
break;
default:
$preString = 'NONE';
break;
}
//CREATING NEW INDEX
$newID = getLastID(); // Get Newest ID from the database
$castNewID = (String) $newID['ID']; //Cast ID to String
$last3chars = substr($castNewID, -3); //Get last three characters of ID
$newIndexNumber = (int) $last3chars + 1; // Cast last3chars to int and add one
$castToString = str_pad((String) $newIndexNumber, 3, "0", STR_PAD_LEFT); //Append zeros to string if we haven't reached 100 yet and cast back into a string.
$newCarID = (String) $preString . (String) $castToString; //Finally create new ID concatenation
//var_dump($newCarID); //For debugging
//INSERT INTO DB
if($TOTAL>=$AVAILABLE)
{
$query = "insert into car (ID,CARNAME,FUELTYPE,TRANSMISSION,ENGINE_SIZE,DOORS,TOTAL,AVAILABLE,DATEADDED)
values ('$newCarID', '$CARNAME', '$FUELTYPE','$TRANSMISSION','$ENGINE_SIZE','$DOORS','$TOTAL','$AVAILABLE',NOW())";
$result = mysql_query($query);
header("location: list_logged.php");
}
else
{
echo "<script>alert('The Total number of cars cannot be less than Available number!'); location.href='add.php';</script>";
}
mysql_close ($link);
?>
In my HTML file I have the following to take input in the following format.
Stuff1,Stuff2,Stuff3,Stuff4
<form action="process_form.php" method="post">
<form>
Part 1: <input type="text" name="p1" /><br />
Part 2: <input type="text" name="p2" /><br />
Part 3: <input type="text" name="p3" /><br />
Part 4: <input type="text" name="p4" /><br />
Part 5: <input type="text" name="p5" /><br />
Part 6: <input type="text" name="p6" /><br />
Part 7: <input type="text" name="p7" /><br />
Part 8: <input type="text" name="p8" /><br />
Part 9: <input type="text" name="p9" /><br />
Part 10: <input type="text" name="10" /><br />
</form>
<input type="submit" name="formSubmit" value="Submit" />
</form>
From there, I am using explode in my php file to separate at the comma and create an array from my string.
$create_table1 = "create table parts(qty int(5) NOT NULL,
partID int(5) NOT NULL PRIMARY KEY,
partname varchar(25) NOT NULL,
price int(5) NOT NULL
)";
$p1_boom = explode(",",$p1);
$p2_boom = explode(",",$p2);
$p3_boom = explode(",",$p3);
$p4_boom = explode(",",$p4);
$p5_boom = explode(",",$p5);
$p6_boom = explode(",",$p6);
$p7_boom = explode(",",$p7);
$p8_boom = explode(",",$p8);
$p9_boom = explode(",",$p9);
$p10_boom = explode(",",$p10);
Now what I am trying to do is enter each set of data on its own line within the table. Such as all the parts of P1 go on the first line in the table, all the parts of P2 go on the next line in the table, etc. Thanks ahead of time for your help and let me know if you need more information!
Do you want the table create code? I am going to assume each part is a TEXT because you haven't specified.... otherwise change the types. Then there is some code to build queries too.
<?php
//find maximum length of $p_booms and the booms
$p_booms = array();
$pb_lengths = array();
for($i = 1; $i <= 10; $i++) {
$p_booms[] = explode(",", $_POST["p$i"]); //not sanitized! (yet)
$pb_lengths[] = count($pb_booms[$i]);
}
$pmax = max($pb_lengths);
//create the table with the maximum width
$create_table = "
CREATE TABLE parts (
partID INT(5) NOT NULL PRIMARY KEY";
for($i = 0; $i < $pmax; $i++) {
$create_table .= ", p$i TEXT DEFAULT NULL";
}
$create_table .= ");";
$mysqli->query($create_table);
//then insert the values by building a query
//I am assuming partID is the p1, p2, p3 becomes 1, 2, 3 respectively
foreach($p_booms as $id => $boom) {
$query = "INSERT INTO parts SET partID=$id";
foreach($boom as $i => $part) {
$part = $mysqli->real_escape_string($part); //yay sanitized!
$query .= ", p$i = '$part'";
}
$mysqli->query($query);
}
Cheers
Your not going to be able to insert an array into a field. You will have to either leave it as a string OR serialize/json_encode the array before inserting. Inserting the rows is no different then inserting any pieces of data.
$db = new PDO(/*connection info*/);
$stmt = $db-prepare('insert into tableName(myColumn) values(?)');
// Just loop throw the data with...
$stmt->execute(array($stringToInsert));
Use the serialize() function.
$p10_boom = explode(",",$p10);
$p10_boom_serial = serialize( $p10_boom );
That produces something like:
a:4:{i:0;s:6:"Stuff1";i:1;s:6:"Stuff2";i:2;s:6:"Stuff3";i:3;s:6:"Stuff4";}
Just escape that string when you save it to your DB.
Now whichever field you are going to use for your data should probably be a text field, or a long VARCHAR field.
If you have to retrieve the value and need to turn it back into an array, use unserialize(). You can convert it back into a string using join() or implode()