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
Related
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.
Im trying to create a form where based on someones first and surname, their email can be changed.
So the html looks like this:
<form action="sUpdateResponse.php" method="post">
<input type="text" placeholder="Enter Email..." name="sUpdateEmail">
Where the name is
<input type="text" placeholder="Enter Forename..." name="sUpdateFN">
<input type="text" placeholder="Enter Surname..." name="sUpdateSN">
<input type="submit" value="Update Records" name="sRetrieveUpdate"></form>
This takes a new email to update the data entry where the forename and surname exist.
The php on sUpdateResponse looks like this,
if($_POST['sRetrieveUpdate'])
$queryRetrieve = mysql_query( "UPDATE staffData SET sEmail='".$_POST['sUpdateEmail']."' WHERE sFN='".$_POST['sUpdateFN']."'
AND sFN='".$_POST['sUpdateSN']."'" );
This doesn't return an error but doesn't seem to alter the email either...
Where am i going wrong?
<?php
if(isset($_POST['sRetrieveUpdate'])){
if(isset($_POST['sUpdateEmail']) && isset($_POST['sUpdateFN']) && isset($_POST['sUpdateSN'])){
$query = "UPDATE staffData SET sEmail = '.$_POST['sUpdateEmail'].' WHERE sFirstName = '.$_POST['sUpdateFN'].' AND sSurName = '.$_POST['sUpdateSN']";
$Result = mysqli_query($query);
}else{
// Error Message
}
}else{
// Error Message
}
?>
"UPDATE staffData SET sEmail='".$_POST['sUpdateEmail']."' WHERE sFN='".$_POST['sUpdateFN'].$_POST['sUpdateSN']."'"
Your Second column is same in where condition sFn repeated.
WHERE sFN='".$_POST['sUpdateFN']."'
AND sFN='".$_POST['sUpdateSN']."'")
It cheks two values in same column . There is your column name mistake in the query.make it correct then it will work fine :)
It should be Something like this
if($_POST['sRetrieveUpdate'])
$queryRetrieve = mysql_query( "UPDATE staffData SET Email='".$_POST['sUpdateEmail']."' WHERE sFN='".$_POST['sUpdateFN']."' AND sSN='".$_POST['sUpdateSN']."'" );
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 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()