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()
Related
i have this form
<form method="post" action="process.php">
Name: <input type="text" name="name" value="">
<br />
English: <input type="text" name="english" value="">
<br />
French: <input type="text" name="french" value="">
<br />
<input type="submit" name="submit" value="Submit">
</form>
and we make this query on process.php
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."'
WHERE
`id` = '".$id."'";
and if i edit the table languages and add more languages the form dynamically will modify to lets say this example
<form method="post" action="process.php">
Name: <input type="text" name="name" value="">
<br />
English: <input type="text" name="english" value="">
<br />
French: <input type="text" name="french" value="">
<br />
Spanish: <input type="text" name="spanish" value="">
<br />
German: <input type="text" name="german" value="">
<br />
<input type="submit" name="submit" value="Submit">
</form>
and the query i need to dynamically be edited
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."',
`german` = '".utf8_encode($german)."'
WHERE
`id` = '".$id."'";
what i don't understand is how i make this dynamically inside the query the code
*the name of the form field is the same of the name of the variable i POST
*and the name of the column from the table is the same of the name of the POST
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."',
`german` = '".utf8_encode($german)."',
`other_language` = '".utf8_encode($other_language)."',
`other_language2` = '".utf8_encode($other_language2)."'
here above i have explained how i make the query but i cant understand how to write the variables
I know is a little bit difficult what i need but maybe someone understand what i need
thank you
Above this line is the edited message because someone flagged this message answered
I will explain first what i want to do:
I have a table called "translations" where i store the languages. ex: english, french, spanish, etc.
I use a form to update the new values, the problem is that i want to do it dynamically not to insert this query on every php file manually because the languages table will grow or edit and i want to work dynamically not to edit every php file.
the variable names are the same like fields name in database
i manage to make an array for the names on table translations
this is what i have until now to make it dynamic
the problem is i don't know how to insert variables in the query $_POST['english'], $_POST['french'], etc
$db = new DB();
$query = $db->query("SELECT * FROM `translations_languages` ORDER BY `name` ASC");
while($row = $query->fetch_assoc()){
$values[] = "`{$row['name']}` = '{$row['name']}'";
}
$dynamic_result = "".strtolower(implode(",", $values))."";
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
$dynamic_result
WHERE
`id` = '".$id."'
";
echo "$query";
and this is how the query looks normally
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."'
WHERE
`id` = '".$id."'";
i want to add these values to the query
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."'
you just need to create a dynamic update array. Something like this:
$languagesToUpdate = array();
// this is an example, you should modify as your script:
// create a variable/constant to make sure you update only allowed fields
$allowedLanguages = array('english' => true, 'french' => true, 'spanish' => true, 'german' => true, 'other_language' => true);
// iterate threw post and check for allowed languages and add to languagesToUpdate the language we need to update with it's value
foreach ($_POST as $post => $value) {
if (isset($allowedLanguages[$post]) && $allowedLanguages[$post]) {
$languagesToUpdate[] = '`' . $post . '` = "' . utf8_encode($value) . '"';
}
}
// add additional data like updated_on
$languagesToUpdate[] = '`updated_on` = ' . time() . '';
//update database
$db = 'UPDATE `translations_structure` SET '.implode(', ', $languagesToUpdate).' WHERE `id` = '.(int)$id;
// this will produce something like this:
// UPDATE `translations_structure` SET `english` = "English text", `spanish` = "Spanish text", `updated_on` = 1479720637 WHERE `id` = 1
Is it possible to POST checkbox name even if its not checked?
<input type='checkbox' class='tinyField' name='alert_by_email' value="1" <?PHP echo $alert_by_emailChecked ?> />
foreach ($_POST AS $field => $value)
$sql[] = $field." = '". $value."'";
$sql = implode(' , ',$sql);
$query = "UPDATE user_setup SET ".$sql." WHERE (userID = ".$userID.") " ;
$res = mysql_query($query);
So when I PRINT_R the POST i will get the field, but it will be empty
Array ( [alert_by_email] => '' )
Add this before your checkbox.
<input type='hidden' name='alert_by_email' value="" />
The straight forward answer is no.
The HTML form wont send the checkbox if it's not checked.
However, there are some workarounds:
use js to Generate a hidden input for each checkbox you have, set the value to 0 or '', and whenever you check them, remove the hidden input.
you could simply test if the key exist in the post like so:
if (isset($_POST['alert_by_email']))
In Short, No this is not possible if you are posting FORM without using any Javascript.
Also, Your code may be injected easily as you are relying on user provided column names without validating those. I am posting alternative way to do that. Hope that helps:
Suppose you have this HTML Form:
<form method="POST">
First name:<br />
<input type="text" name="firstname" />
<br />
Last name:<br />
<input type="text" name="lastname" /><br />
<input type="submit" />
</form>
Now, if you want to update values using PHP, your code should be:
<?php
$columnArray = array('firstname' => NULL, 'lastname' => NULL); // This is list of columns which can be updated using form input values (NULL is default value here)
$submittedValues = array_intersect_key($_POST, $columnArray);
// Above code will produce an array like `array('firstname' => 'anyname', 'lastname' => 'anylastname')
//--> Now you can generate your SQL using `$submittedValues`
$sql = array();
foreach ($submittedValues as $field => $value)
{
$sql[] = $field." = '". $value."'";
}
$sqlString = implode(' , ',$sql);
Using this way, hacker will not be able to add extra columns which shouldn't be updated by user i.e. last_login_date or something.
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);
?>
I'm submitting a form via HTML into a POST PHP page, which is then storing that info into the MySQL database. One of the input fields is a number field that can start with zero. I've set the HTML data type to text on the form and tried setting the MySQL data type to text and varchar, and both times the zero before the integer gets dropped. I'm not quite sure what I'm doing wrong.
Here is my PHP code for table creation:
$sql = "CREATE TABLE IF NOT EXISTS $tablename_db (
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
num text(4),
amnt DECIMAL(8,2)
);";
And here is what the form field looks like:
<div id="input1" class="cinput">
# (last 4 digits): <input id="cnum" type="text" name="num[]" maxlength="4" size="4" /> Amount: <input id="camnt" type="int" name="amnt[]" /> </br>
</div>
Using this, a number like 0125 inputted to 'cnum' is saved as 125. What am I doing wrong?
EDIT: Here is the code in its entirety, just so it's clear what I'm doing. It's not a very long code (possible typos as I tried to transfer things onto here).
<?php
if(isset($_POST['submit']))
{
//Get Current User Login
global $current_user;
$current_user = wp_get_current_user();
$ulog = $current_user->user_login;
$tablename = "db_".$ulog;
//Check To See If User Has Already Created Table
$sql = "CREATE TABLE IF NOT EXISTS $tablename (
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
num text(4),
amnt DECIMAL(8,2)
);";
mysql_query($sql);
$num = $_POST['num'];
$amnt = $_POST['amnt'];
$items = array_combine($num,$amnt);
$pairs = array();
foreach($items as $key=>$value)
{
if($key != 'submit')
{
if($value != '')
{
$pairs[] = '('.intval($key).','.intval($value).')';
}
}
}
if (!mysql_query('INSERT INTO ' .$tablename. '(num, amnt) VALUES '.implode(',',$pairs)))
die('Error: ' . mysql_error());
else
echo '<strong>', "Your information has been submitted and will be added to your account upon approval.", '</strong>', "/n";
}
?>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.ccinput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 20 names
if (newNum == 20)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.ccinput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
</head>
<body>
Please fill in your information in the form below and press submit. If you need to add more, please click the "Add" button at the bottom of the form. You may enter a maximum of 20 at a time. Leave all unused fields blank.
<form method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<fieldset>
<legend>Information:</legend>
<div id="input1" class="ccinput">
# (last 4 digits): <input id="cnum" type="text" name="num[]" maxlength="4" size="4" /> Amount: <input id="camnt" type="int" name="amnt[]" /> </br>
</div>
<div>
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnDel" value="Remove" />
</div>
</fieldset>
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
After much debugging, I believe that the error is somewhere in these two sections.
Section 1:
$sql = "CREATE TABLE IF NOT EXISTS $tablename_db (
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
num text(4),
amnt DECIMAL(8,2)
);";
Or it might be in this line:
if (!mysql_query('INSERT INTO ' .$tablename. '(num, amnt) VALUES '.implode(',',$pairs)))
The code seems to maintain the format perfectly all the way up to this line. Therefore I think that the zero is being dropped while being inserted into the MySQL database. I'm not sure why it's doing it though...
intval() means "take the string and convert it to an integer", and this is what is causing the string "01234" to come out as the number 1234.
Remove it from $pairs[] = '('.intval($key).','.intval($value).')'; and for the number field, since you want to insert it as text; encapsulate it in quotes '$value'.
You are converting your string to int at this line:
$pairs[] = '('.intval($key).','.intval($value).')';
After that, you do the insert, using the values from $pairs (which now contains two integers):
mysql_query('INSERT INTO ' .$tablename. '(num, amnt) VALUES '.implode(',',$pairs))
You should replace:
$pairs[] = '('.intval($key).','.intval($value).')';
with:
$pairs[] = '('.$key.','.$value.')';
Someone helped me realize my mistake. I was missing a quotation in the $pairs[] line and instead of entering it into MySQL as a string, it was going in as an integer and that's why MySQL was dropping the zero. Everything is working perfectly now.
instead of intval you can use something like this
function toNumeric($str)
{
return is_numeric($str) ? $str : preg_replace('/\D/',null,$str);
}
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
}