Insert two arrays in database - php

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

Related

php POST form query update dinamic variables [duplicate]

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

Increment double-bracket PHP arrays to SQL

Here is a example of what my form looks like.
<div>
<input name="address[1][name]" type="text">
<input name="address[1][street]" type="text">
<input name="address[1][city]" type="text">
<input name="address[1][phone]" type="text">
</div>
<div>
<input name="address[2][name]" type="text">
<input name="address[2][street]" type="text">
<input name="address[2][city]" type="text">
<input name="address[2][phone]" type="text">
</div>
...
I'd like to increment the data obtained from each block in PHP and increment it into my database with MySQL.
What is the best way to achieve this ?
I know it generates arrays, but I do not know how to deal with the "double-bracket" method (the form "aaa[x][bbb]" probably has a proper name, which I do not know, I'm sorry).
Thanks.
If you want to iterate over all fields using double brackets, the best structure to use are nested foreach's:
$formdata = $_POST['address'];
foreach($formdata as $group)
{
$SQLFields = array();
$SQLValues = array();
foreach($group as $field => $value)
{
// Here you have each individual field inside each group, so you can
// build the fields of the INSERT statement.
$SQLFields[] = $field;
$SQLValues[] = $value;
}
// Now assemble everything, and your INSERT is ready.
$SQL = "insert into table (".
implode(", ", $SQLFields).
") values ('".
implode("', '", $SQLValues).
"')";
// Run the SQL statement the way you want.
}
I think you are looking for something like this:
$data = $_POST['address'];
foreach($data as $address) {
//your address-object (name, street, city, phone)
var_dump($address);
//Add your sql-query in here and DO NOT forget to escape your received data
}

how to search array of checkboxes

Im building a search form but how do you search a array of checkboxes?
here is my html form
<form method="get">
<label>
<input type="checkbox" name="material[]" value="metal">metal
</label>
<label>
<input type="checkbox" name="material[]" value="plastic">Plastic
</label>
<label>
<input type="checkbox" name="material[]" value="carbon">Carbon
</label>
<input type="text" name="keyword">
<input type="submit" value="search">
</form>
and the php so far is. So how can i search the material for each checked.
<?php
if(isset($_GET['keyword'])){
$keyword = $_GET['keyword'];
// $material = $_GET['material'];
// $Search->search($keyword);
}
?>
ANd the query would be so far
$query = $this->pdo->prepare('SELECT * FROM `shop` WHERE `material` = ?');
When posted this will submit an array named material (accessible via $_GET['material']) that contains only the values that were checked.
You can then use those or output them like this:
foreach ($_GET['material'] AS $material) {
echo $material;
}
Addition after the question was edited:
You can also implode() the array values with ', ' as glue and use that as the search parameter in your SQL statement. Just change it to use IN instead of =, like #Prashant M Bhavsar suggested in his answer.
I think this will help you
Get your submitted material array in variable
$material_array = $_POST['material'];
You can implode array in select query to fetch related result
$selected_search_material = implode(',', $material_array);
SELECT * FROM `shop` WHERE `material` IN ($selected_search_material)
I haven't tested this yet, but since you receive an array ($_get['material'] is already an array), just use the following code with find_in_set;
<?php
$materials = array();
if (array_key_exists('material', $_GET)) {
$materials = $_GET['material'];
}
$query = $this->pdo->prepare('SELECT * FROM `shop` WHERE find_in_set(cast(material as char), :materials');
$query->execute(array('materials' => $materials));
?>
Implode $_GET['material'] and use a different query:
$where = implode(', ',$_GET['material']);
$query = $this->pdo->prepare('SELECT * FROM `shop` WHERE `material` IN ?');
Then use $where in your execute();
You can use $materialValue to store into Database.
<?php
if(isset($_GET['material'])){
$material = $_GET['material'];
foreach($material as $materialIndex){
$materialValue .= $materialIndex.',';
}
}
// use value to store into db
pass $materialValue variable to IN query also remove last "," from string
$materialValue.substring(0,$materialValue.length()-1);
?>

Using jQuery serialize to put ajax values into a database select query

I have the following code:
<?php
$allform = $_POST['allform'];
parse_str($allform, $output);
$allquery = "SELECT * FROM wp_users";
$names = array();
$allresult = mysql_query($allquery) or die(mysql_error()); ?>
...
<?php
while ($rows = mysql_fetch_array($allresult)) {
$names[] = $rows['user_email'];
}
?>
The allform variable is a jQuery serialize string:
var allform = $('form#all').serialize();
Basically, I want to put the values from the form in the front end into a mysql select query in the back end.
The form is a bunch of checkboxes so the idea is that the SELECT something will have different number of values depending on what the user checks. Any ideas?
Thanks
The best thing to do could be something like this. Your checkboxes should be like this
<input type="checkbox" name="checkboxes[]" value="cream" />
<input type="checkbox" name="checkboxes[]" value="choco" />
<input type="checkbox" name="checkboxes[]" value="lime" />
server side you receive an array
$flavours = $_POST["checkboxes"];
$sql = "SELECT ".implode(',', $flavours)." FROM FLAVOURTABLE";

loop to update data coming from form php mysql html

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
}

Categories