Iterate through arrays and input into database - php

I have a form with capturing data and posting in an array named "table" so the tables, columns and tuples are linked.
I am now trying to iterate through them and seperate them into there individual strings,
"$table" = name
"$columns" = columns
"$columnData" = data
When i do a var_dump on the data, it looks like:-
array (size=2)
0 =>
array (size=3)
'name' => string 'quote' (length=5)
'columns' =>
array (size=3)
0 => string 'qid' (length=3)
1 => string 'item' (length=4)
2 => string 'price' (length=5)
'data' =>
array (size=3)
0 => string '1' (length=1)
1 => string 'ball' (length=4)
2 => string '200' (length=3)
1 =>
array (size=3)
'name' => string 'rfq' (length=3)
'columns' =>
array (size=2)
0 => string 'id' (length=2)
1 => string 'item' (length=4)
'data' =>
array (size=2)
0 => string '1' (length=1)
1 => string 'batt' (length=4)
Which looks in the correct format, although when i try to insert into the database it does not insert, there is something about the $columns variable in the insert statement that does not work.
Although I am unsure if i am iterating through the data correctly.
$AllData = $_POST["table"];
// var_dump($AllData)
foreach ($AllData as $sigleData) {
$table = $sigleData['name'];
$columns = implode(" ", $sigleData['columns']);
$columnData = implode(" ", $sigleData['data']);
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
if ($dbConnectionT->query($sqlQuery) == TRUE) {
echo "database updated";
echo "</br>";
}
}
So table quote has columns qid, item and price.
with values 1, ball and 200 which i am trying to insert correctly into.
Please note, I understand the database violations here, but trying to get the programming example working,
If the previous page is required, please comment. Thanks in advance.

Try with -
foreach ($AllData as $sigleData) {
$table = $sigleData['name'];
$columns = implode(", ", $sigleData['columns']);
$columnData = implode(" ',' ", $sigleData['data']);
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
if ($dbConnectionT->query($sqlQuery) == TRUE) {
echo "database updated";
echo "</br>";
}
}

In your insert query you are building VALUE part with a single ' for both values... Just change the implode param with "', '"

Related

PHP Associative Array in table iterate columns

I get this array from a mysql query:
array (size=9)
0 =>
array (size=2)
'room_category' => string 'MALE GENERAL WARD' (length=17)
'vacant_beds' => string 'MG-8,MG-2,MG-4,MG-6,MG-7' (length=24)
1 =>
array (size=2)
'room_category' => string 'FEMALE GENERAL WARD' (length=19)
'vacant_beds' => string 'FG-4,FG-1,FG-2,FG-3' (length=19)
2 =>
array (size=2)
'room_category' => string 'MOTHER CHILD WARD' (length=17)
'vacant_beds' => string 'MC-2,MC-4,MC-5,MC-6' (length=19)
3 =>
array (size=2)
'room_category' => string 'TWIN' (length=4)
'vacant_beds' => string 'TW-A1,TW-A2,TW-B2,TW-C1,TW-C2' (length=29)
4 =>
array (size=2)
'room_category' => string 'NICU' (length=4)
'vacant_beds' => string 'NICU-6,NICU-1,NICU-7,NICU-3,NICU-8,NICU-4,NICU-5' (length=48)
5 =>
array (size=2)
'room_category' => string 'CLASSIC' (length=7)
'vacant_beds' => string 'CL-6,CL-8,CL-4,CL-5' (length=19)
6 =>
array (size=2)
'room_category' => string 'DELUXE' (length=6)
'vacant_beds' => string 'DLX-5,DLX-6' (length=11)
7 =>
array (size=2)
'room_category' => string 'EXECUTIVE' (length=9)
'vacant_beds' => null
8 =>
array (size=2)
'room_category' => string 'AC GENERAL WARD' (length=15)
'vacant_beds' => string 'AG-5,AG-1,AG-2,AG-3,AG-4' (length=24)
Now I want to display this array in html table.
I have tried this, where I can achieve it only partly.
I want the string part that is string 'MG-8,MG-2,MG-4,MG-6,MG-7' to be in separate columns.
echo "<table>";
foreach($rows as $key=>$row) {
echo "<tr>";
foreach($row as $key2=>$row2){
echo "<td>" . $row2 . "</td>";
}
echo "</tr>";
}
echo "</table>";
from which I get table like below
MALE GENERAL WARD MG-8,MG-2,MG-4,MG-6,MG-7
FEMALE GENERAL WARD FG-4,FG-1,FG-2,FG-3
MOTHER CHILD WARD MC-2,MC-4,MC-5,MC-6
TWIN TW-A1,TW-A2,TW-B2,TW-C1,TW-C2
NICU NICU-6,NICU-1,NICU-7,NICU-3,NICU-8,NICU-4,NICU-5
CLASSIC CL-6,CL-8,CL-4,CL-5
DELUXE DLX-5,DLX-6
EXECUTIVE
AC GENERAL WARD AG-5,AG-1,AG-2,AG-3,AG-4
Every item of your comma-separated string can be received by exploding string by ,. But as every string can have different number of elements - first you need to find the value of max elements. Thus you need to iterate $rows twice - first find max count of elements and second - echo tds. So we can do this:
echo "<table>";
$new_rows = [];
$max_count = 0;
foreach ($rows as $key => $row) {
$elements = [];
if (!empty($row['vacant_beds'])) {
$elements = explode(',', $row['vacant_beds']);
if (sizeof($elements) > $max_count) {
$max_count = sizeof($elements);
}
}
$new_rows[] = [
'name' => $row['room_category'],
'elements' => $elements,
];
}
foreach ($new_rows as $row) {
echo '<tr>';
// echo name
echo '<td>' . $row['name'] . '</td>';
// main part - items in elements we will wrap into `td`:
foreach ($row['elements'] as $e) {
echo '<td>' . $e . '</td>';
}
// if number of elements in `$row['elements']` is less
// than `$max_count` - we should add empty `<td>`
if (sizeof($row['elements']) < $max_count) {
echo str_repeat('<td></td>', $max_count - sizeof($row['elements']));
}
echo '</tr>';
}
echo "</table>";
Handle the needed key(in your case - vacant_beds) for further processing:
echo "<table border='1'>";
foreach($rows as $row) {
echo "<tr>";
foreach($row as $key => $row2){
echo "<td>" .
(($key == 'vacant_beds')? implode("</td><td>", explode(",", $row2)) : $row2)
. "</td>";
}
echo "</tr>";
}
echo "</table>";

Multiple where condition codeigniter active record

I want to make a multiple where query with AND and OR. Suppose my array is:
array (size=8)
0 => array (size=2)
'timeline.type' => string 'videos' (length=6)
'timeline.sourceId' => string '7' (length=1)
1 => array (size=2)
'timeline.type' => string 'loadshedding' (length=12)
'timeline.sourceId' => string '5' (length=1)
2 => array (size=2)
'timeline.type' => string 'news' (length=4)
'timeline.sourceId' => string '3' (length=1)
3 => array (size=2)
'timeline.type' => string 'news' (length=4)
'timeline.sourceId' => string '5' (length=1)
The above array could be dynamic. I want to make active record query like:
(timeline.type = 'videos' AND timeline.sourceId = 7) OR (timeline.type = 'loadshedding' AND timeline.sourceId = 5) OR (timeline.type = 'news' AND timeline.sourceId = 3) // and so on.
I tried :
$this->db->select('timeline.id as postid, timeline.*, sources.*, subscription.*')->from('timeline');
$this->db->join('sources', 'sources.type = timeline.type and timeline.sourceId = sources.id');
$this->db->join('subscription', 'subscription.type = timeline.type and timeline.sourceId = subscription.sourceId');
foreach($sources as $source){ //$sources is an array like given above
$this->db->or_where($source);
}
$this->db->order_by("timeline.id", "DESC");
$this->db->limit(15);
But when I echo $this->db->last_query(); to see the query. It returns SELECT * FROM timeline only. What might be the problem. Thank you.
Your Code Should be like
$sources = array (
0 => array (
'timeline.type' => 'videos',
'timeline.sourceId' => '7' ),
1 => array (
'timeline.type' => 'loadshedding',
'timeline.sourceId' => '5' ) ,
2 => array (
'timeline.type' => 'news',
'timeline.sourceId' => '3' ),
3 => array (
'timeline.type' => 'news',
'timeline.sourceId' => '5')
);
end($sources); // move the internal pointer to the end of the array
$lastkey = key($sources);
$pr = "";
foreach($sources as $key=>$source)
{
if($key != $lastkey)
{
$pr.="( `timeline.type` = '". $source["timeline.type"] ."' and `timeline.sourceId` = " . (int) $source["timeline.sourceId"] . ") OR ";
}
else
{
$pr.="( `timeline.type` = '". $source["timeline.type"] ."' and `timeline.sourceId` = " . (int) $source["timeline.sourceId"] . ")";
}
}
$this->db->select('timeline.id as postid, timeline.*, sources.*, subscription.*')->from('timeline');
$this->db->join('sources', 'sources.type = timeline.type and timeline.sourceId = sources.id');
$this->db->join('subscription', 'subscription.type = timeline.type and timeline.sourceId = subscription.sourceId');
$this->db->where($pr);
$this->db->order_by("timeline.id", "DESC");
$this->db->limit(15);

Combine all values and remove duplicates

How combine this array and remove duplicate values?
Thank you!
array (size=17)
0 => string 'Black' (length=5)
1 => string 'Blue' (length=4)
2 => string 'Burgundy' (length=8)
3 => string 'Glow' (length=4)
4 => string 'Granite' (length=7)
5 => string 'Green' (length=5)
6 => string 'Lime' (length=4)
7 => string 'Natural' (length=7)
8 => string 'Orange' (length=6)
9 => string 'Pink' (length=4)
10 => string 'Purple' (length=6)
11 => string 'Red' (length=3)
12 => string 'Silver' (length=6)
13 => string 'Teal' (length=4)
14 => string 'Violet' (length=6)
15 => string 'White' (length=5)
16 => string 'Yellow' (length=6)
Thank you, your code worked perfectly.
I'm still missing something because I don't get what I want.
The values (color names) are in the select form, but when a value other than 'Filter by Color' is selected, the 'id' is what pass instead of the 'text'. To make things easy, here is the complete code.
Thank you.
$Sql_product_colors = ("SELECT COUNT(p.products_id) AS id, pia.product_filter_colors FROM products p LEFT JOIN products_imprint_areas pia on p.products_id = pia.products_id
WHERE p.products_id > '1'
AND pia.product_filter_colors IS NOT NULL
GROUP BY product_filter_colors
ORDER BY product_filter_colors asc");
$sort_list_colors = array();
$product_filter_colors = tep_db_query($Sql_product_colors) or die(mysql_error());
while ($row = mysql_fetch_array($product_filter_colors)) {
$arrColor = explode(',', $row[1]);
$arrColors=array_filter(array_map('trim', $arrColor));
$sort_list_color = array_merge($sort_list_colors,$arrColors);
$sort_list_colors = array_unique($sort_list_color);
sort($sort_list_colors);
}
$sort_list_colors[0] ='Filter by Color';
$sort_list_colors[] =' '.$row[$sort_list_colors].' (' .$sort_list_colors['count'].')';
if(count($sort_list_colors)>0)
{
foreach($sort_list_colors as $id=>$text) {
$sort_range_colors[] = array('id' => $id, 'text' => $text);
}
}
// -------------------------------------- Select form
echo '<td align="center" width="25%" valign="middle"><div class="styled-select">' . tep_draw_form('colors_sort', htmlentities($_SERVER['PHP_SELF']), 'get') . '';
echo tep_draw_pull_down_menu('colors_sort', $sort_range_colors, (isset($HTTP_GET_VARS['colors_sort']) ? $HTTP_GET_VARS['colors_sort'] : ''), 'onchange="this.form.submit()"');
echo '</form></div></td>';
This is the function tep_draw_pull_down_menu. Thank you.
function tep_draw_pull_down_menu($name, $values, $default = '', $parameters = '', $required = false) {
$field = '<select name="' . tep_output_string($name) . '"';
if (tep_not_null($parameters)) $field .= ' ' . $parameters;
$field .= '>';
if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]);
for ($i=0, $n=sizeof($values); $i<$n; $i++) {
$field .= '<option value="' . tep_output_string($values[$i]['id']) . '"';
if ($default == $values[$i]['id']) {
$field .= ' SELECTED';
}
$field .= '>' . tep_output_string($values[$i]['text'], array('"' => '"', '\'' => ''', '<' => '<', '>' => '>')) . '</option>';
}
$field .= '</select>';
if ($required == true) $field .= TEXT_FIELD_REQUIRED;
return $field;
}
Use array_merge then array_unique,
$colors = array();
while ($row = mysql_fetch_array($filter_colors)) {
$arrColors = explode(',', $row[1]);
$colors = array_merge($colors,$arrColors);
}
$colors = array_unique($colors);
Warning: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

pb for build an HTML table with table PHP

I try to make a table html, with 2 table PHP,
I don't manage to put my value which is in my 4th row, 3th column in the 4th row, 4th column.
My PHP/html:
<table BORDER=1px>
<tr>
<?php
foreach($tableau1 as $value)
{
echo '<th>'.$value.'</th>';
}
?>
</tr>
<?php
foreach($tableau as $valu)
{
echo '<tr>';
foreach($tableau1 as $val => $ke)
{
foreach($valu as $vava => $keke)
{
if($val==$vava){echo '<td>'.$keke.'</td>';}
}
}
echo '</tr>';
}
?>
</table>
My PHP table (first:table , second:table1)
array (size=3)
6 =>
array (size=2)
'marque' => string 'marque 6' (length=8)
'modele' => string 'modele 6' (length=8)
3 =>
array (size=4)
'marque' => string 'marque 3' (length=8)
'modele' => string 'modele 3' (length=8)
2 => string 'bois art3' (length=9)
4 => string 'beton art3' (length=10)
5 =>
array (size=3)
'marque' => string '-lepetit' (length=8)
'modele' => string 'modele 5' (length=8)
4 => string 'beton art5' (length=10)
array (size=4)
'marque' => string 'marque' (length=6)
'modele' => string 'modèle' (length=6)
2 => string 'bois' (length=4)
4 => string 'beton' (length=5)
Response to first answer:
:) I already tried it but it's not good I get too much cell in all row and I don't understand why ...
I think you need to print an empty <td></td> when no data for the cell.
<?php
foreach($tableau as $valu)
{
echo '<tr>';
foreach($tableau1 as $val => $ke)
{
$found = false;
foreach($valu as $vava => $keke)
{
//echo '<td>' . $val . ' ' . $vava . ' ' . $keke . '</td>';
if($val==$vava){
echo '<td>'.$keke.'</td>';
$found = true;
}
}
if (!$found) { echo '<td></td>'; }
}
echo '</tr>';
}
?>
Added a boolean to flag when data was added to the column and then moved the
echo '<td></td>';
outside of the inner loop.

Store value in multi-dimentional array on unique key

How do I display the following using the array shown below?
Pastors
key=>0, member_id, member_name
Deacons
key=>1, member_id, member_name
key=>2, member_id, member_name
Here is the array.
array (size=3)
0 =>
array (size=4)
'category_name' => string 'Pastors' (length=7)
'member_id' => string '3' (length=1)
'member_name' => string 'Tiny Marshall' (length=13)
'member_email' => string 'jconley#nowhere.com' (length=19)
1 =>
array (size=4)
'category_name' => string 'Deacons' (length=7)
'member_id' => string '1' (length=1)
'member_name' => string 'Jeremiah Conley' (length=15)
'member_email' => string 'jconley#nowhere.com' (length=19)
2 =>
array (size=4)
'category_name' => string 'Deacons' (length=7)
'member_id' => string '2' (length=1)
'member_name' => string 'Marcy Conley' (length=12)
'member_email' => string 'jconley#nowhere.com' (length=19)
Here is the code that I used to build the array:
while( $row = mysql_fetch_assoc( $result ) )
{
$staff[$i] = array
(
'category_name' => $row['category_name'],
'member_id' => $row['member_id'],
'member_name' => $row['member_name'],
'member_email' => $row['member_email'],
);
$i++;
}
This is the final solution:
$category_name = array();
foreach ($staff as $member) {
if (!in_array( $member['category_name'], $category_name ))
{
echo '<h1>' . $member['category_name'] . '</h1>';
$category_name[] = $member['category_name'];
}
echo $member['member_id'] . ', ' . $member['member_name'] . '<br />';
}
Use foreach to loop over your $staff array.
$pastors = array();
$deacons = array();
foreach ($staff as $member) {
if ($member['category_name'] == 'Pastors') {
$pastors[] = $member['member_id'] . ', ' . $member['member_name'];
} else if ($member['category_name'] == 'Deacons') {
$deacons[] = $member['member_id'] . ', ' . $member['member_name'];
}
}
documentation

Categories