How to insert multiple records to MySQL - php

i have small page with cart. All things is storage in session. Now i need to save this data to mysql databse.
I think, that i need use foreach cycle to do this, but i cant construct it. Does anybody know the solution?
This is the function that displays cart.
function showCart() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
$total=0;
$output[] = '<table>';
foreach ($contents as $id_menu=>$qty) {
$sql = 'SELECT * FROM menu WHERE id_menu = '.$id_menu;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td>Delete</td>';
$output[] = '<td>' .$name. '</td>';
$output[] = '<td>' .$price.' Kč</td>';
$output[] = '<td><input type="text" name="qty'.$id_menu.'" value="'.$qty.'" size="5" maxlength="5" /></td>';
$output[] = '<td>' .($price * $qty).' Kč</td>';
$total += $price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$output[] = '<p>Total: <strong>'.$total.' EUR</strong></p>';
$output[] = '<div><button type="submit">Update</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>Cart is empty.</p>';
}
return join('',$output);
}

i think you need something like this....
foreach ($contents as $id_menu=>$qty)
{
$sql1 = 'INSERT INTO tablename (colum1, colum2, column3, ... ) SELECT * FROM menu WHERE id_menu = '.$id_menu;
//rest of your program
}

You can use:
Insert into mytable SELECT * FROM menu WHERE id_menu = ...
To construct the multiple insert and insert all in one statement, do the following:
Insert into mytable (col1, col2, col3) values
('Val1a','val2a','val3a'),
('Val1b','val2b','val3b'),
('Val1f','val2d','val3c'),
Etc...
;
Each iteration will concatenate one line of values. Insert is then done after the loop.

Related

Warp two row with a class after query

I want to warp every two row with a class. So I saw some guideline from here and googling and found foreach array_chunk to do this. And I tried as below which can't display any result. Without foreach its work well. Were is my wrong here please?
In the above picture that I want to do; my every two category warp with a class. And add a divider after each top category.
Here is my tried:
echo '<ul class="dropdown-menu dropdown-menu-large row">';
$sql = "SELECT id,name FROM main_cata ORDER BY id ASC";
$execute = $dbh->query("$sql");
$rowcount = $execute->num_rows ;
$row = $dbh->query($sql) ;
while ($row = $execute->fetch_assoc()) {
foreach (array_chunk($row, 2, true) as $array){
echo'<li class="col-sm-3">';
foreach($array as $rows){
echo '<ul><li class="dropdown-header">'.$rows->name.'</li>';
$sql2 = "SELECT id,name,page FROM catagory WHERE m_cata = '".$rows->id."' ORDER BY id ASC";
$execute2 = $dbh->query("$sql2");
$rowcount2 = $execute2->num_rows ;
$row = $dbh->query($sql) ;
while ($row = $execute2->fetch_assoc()) {
$cid = $row['id'];
$cname = $row['name'];
$page = $row['page'];
echo '<li>'.$cname.'</li>';
}
echo '<li class="divider"></li></ul>';
}
echo '</li>';
}
}
echo '</ul>';
while ($row = $execute->fetch_assoc()) {
fetch_assoc returns 1 row (id, name) from the query, then you are using the result and spliting in 2 (https://secure.php.net/manual/pt_BR/mysqli-result.fetch-assoc.php), What you can do is, make a counter instead of the array chunk that resets every time it reachs 2.
foreach (array_chunk($row, 2, true) as $array){
The content of $row is, for example, array('id' => 1, 'name' => 'Category 1').
foreach($array as $rows){
You are iterating again without needing to.
A simple version:
counter = 0;
echo "<ul>";
while (row = execute->fetch_assoc()) {
if (counter == 0) {
echo "init li";
}
echo "subinit li";
get subcategories
while (row2 = execute2->fetch_assoc()) {
print content
}
echo "subend li";
if (counter == 2) {
counter == 0;
echo "end li";
} else {
counter++;
echo "divider";
}
}
echo "</ul>";

How can I sort by variable within a foreach loop (php)?

in my for each loop I want to sort my options by the value of my variable $total resp. by the data-total:
<select>
<option data-total="0" value="" selected>--</option>
<?php
$pdo = Database::connect();
$sql = "SELECT * FROM table_a;" ;
foreach ($pdo->query($sql) as $row) {
$a = $row['a'];
$number_a = $row['number_a'];
$sql2 = "SELECT * FROM table_b WHERE a = '$a';" ;
$number_b = 0;
foreach ($pdo->query($sql2) as $row2) {
$number_b+= $row2['number'];
}
$total = $number_a - $number_b;
echo '<option data-total="'.$total.'" value="'.$a.'">'.$a;
}
Database::disconnect();
?>
</select>
Is this possible? Thank you very much!
In your for loop do something like this
$total_arr = array();
foreach ($pdo->query($sql) as $row) {
$a = $row['a'];
$number_a = $row['number_a'];
$sql2 = "SELECT * FROM table_b WHERE a = '$a';" ;
$number_b = 0;
foreach ($pdo->query($sql2) as $row2) {
$number_b+= $row2['number'];
}
$total = $number_a - $number_b;
$total_arr[$a] = $total;
}
arsort($total_arr);
foreach ($total_arr as $key => $val) {
echo '<option data-total="'.$val.'" value="'.$key.'">'.$key;
}

Convert array to another array

I have one array that I am showing like this:
echo '<table>';
foreach ($rowData as $row => $tr) {
echo '<tr>';
foreach ($tr as $td)
echo '<td>' . $td .'</td>';
echo '</tr>';
}
echo '</table>';
The second and fourth columns are always the name of the column. The result is something like:
Name: John Locke - NickName: Locke
Age: 20 - Adress: Ok
See the pattern?
How can I put these array in my database?
As my database table structure is:
ID - Name - NickName - Age - Adress
I don't have a clue how to do that with the array i'm using..
--UPDATE
$table = $html->find('table', 0);
$rowData = array();
foreach($table->find('tr') as $row) {
// initialize array to store the cell data from each row
$flight = array();
foreach($row->find('td') as $cell) {
foreach($cell->find('span') as $e){
$e->innertext = '';
}
// push the cell's text to the array
$flight[] = $cell->plaintext;
}
$rowData[] = $flight;
}
echo '<table>';
foreach ($rowData as $row => $tr) {
echo '<tr>';
echo '<td>' . $row . '</td>';
foreach ($tr as $td)
echo '<td>' . $td .'</td>';
echo '</tr>';
}
echo '</table>';
you can do that:
$insert = "";
foreach ($rowData as $row => $tr) {
$insert .= "('".$tr[0]."','".$tr[0]."','".$tr[0]."','".$tr[0]."'),";
}
$insert = substr($insert, 0, -1)
$sql = "Insert into YourTable values ".$insert;
As you already know what the array positions relate to, IE positions 0 through 3. You can simply iterate as you are doing now and compile a query instead.
Just drop this snippet into your code, ive knocked this up on the fly and its a bit hackish, probably a better way. Just look at what it does on your screen and see where if any it needs correcting.
$insert = '';
for ($i=0; $i<=3; $i++):
$insert .= "'" . $tr[$i] . "'";
if ($i !== 3):
$insert .= ',';
endif;
endfor;
echo $insert;
Once you are seeing what looks like a correct insert then you can (using safe methods) insert it into your database.

products duplicate in shoppingcart

When I add multiple products to the shopping cart, it duplicates the product data which was first inserted. The prepare statement in showCart() also echo's 'There's something wrong', while the data is still displayed, I suppose my code looks quite nasty. Excuses for that, I'm planning on cleaning it, when I get it to function
public function displayProduct()
{
if($product = $this->db->query("SELECT id, title, description, price FROM trips ORDER BY id"))
{
while ($row = $product->fetch_assoc())
{
$output[] = '<div class="reisbox">';
$output[] = '<div id="reis_insidebox1">';
$output[] = '<div class="reis_textbox">';
$output[] = '<h2>'.ucfirst($row['title']).'</h2>';
$output[] = '<article>';
$output[] = ucfirst($row['description']);
$output[] = '</article>';
$output[] = '</div>';
$output[] = '<div class="rightboxx">';
$output[] = '<div class="reis_price_box">';
$output[] = '<div class="reis_price_box_text">';
$output[] = '€'.$row['price'];
$output[] = '</div>';
$output[] = '<div class="more_box">';
$output[] = '<p>Lees meer..</p>';
$output[] = '</div>';
$output[] = '</div>';
$output[] = '</div>';
$output[]='<br />';
$output[] = '<div id="add">';
$output[]='Add to cart';
$output[] = '</div>';
$output[] = '<div class="review_box">';
$output[] = '<div class="review_text">Review</div>';
$output[] = '<div class="review_textbox"> Fantastische ontvangst met kleine attenties. Fantastisch ontbijt,. Goede bedden en ruime zitgelegenheid in de serre.</div>';
$output[] = '<div class="star_box"></div>';
$output[] = '<div class="review_linkbox">';
$output[] = 'Schrijf review';
$output[] = '</div>';
$output[] = '</div>';
$output[] = '</div>';
}
echo implode($output);
}
public function showCart() {
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[]='<div id="contents">';
$output[] = '<form action="index.php?page=cart.php&action=update" method="post" id="cart">';
$output[]='<table id="table_cart">';
$output[]='<thead>';
$output[]='<tr>';
$output[]='<th scope="col"></th>';
$output[]='<th scope="col">Informatie</th>';
$output[]='<th scope="col">Prijs</th>';
$output[]='<th scope="col">Aantal</th>';
$output[]='<th scope="col">Prijs Totaal</th>';
$output[]='</tr>';
$output[]='</thead>';
foreach ($contents as $id=>$qty)
{
$sql = 'SELECT id, title, description, price FROM trips WHERE id = ?';
if($result = $this->db->prepare($sql))
{
$result->bind_param('i', $id);
$result->execute();
$result->bind_result($id, $title, $description, $price);
$result->fetch();
}
else
{
echo "something went wrong";
}
$output[]='<tr>';
$output[]='<td><p>Remove</p></td>';
$output[]='<td>'.$title.'</td>';
$output[]='<td>€'.$price.'</td>';
$output[]='<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[]='<td>€'.($price * $qty).'</td>';
$total += $price * $qty;
$output[]='</tr>';
}
$output[] = '<div id="total">';
$output[] = '<p>Grand total: <strong>€'.$total.'</strong></p>';
$output[] = '<button type="submit">Update cart</button>';
$output[] = '</div">';
$output[] = '</table>';
$output[]='</form>';
$output[] = '</div">';
} else {
$output[] = '<p>You shopping cart is empty.</p>';
$output[] = '<p>terug naar reizen</p>';
}
return implode('',$output);
}
First off, this is two separate bugs, and unless there is something else going on you aren't telling us the first script has nothing to do with either.
Bug 1: If your script echos "something went wrong" during a call to showCart() then you should be debugging your database connection and your statement prepare. Unless some of those column names or the row name is wrong, the error will most likely be in your connection. Try echoing the DB error info to see what is going on.
Bug 2: duplicated product data when showing cart:
To properly debug this we'd need to see how you add a product to the cart in the first place, but likely however you do so is interacting with this line negatively:
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
EDIT
Actually it probably isn't that line causing the second bug, it probably is the fact that you echo product info even if the DB call fails.

Multi level selectbox

I have a problem with building multi level select box. I have category table with structure: id, parent_id, name. If parent_id = 0 it is top level. i don't know level depth, so it could be 2,3-5 levels.
How i can build it with on query "SELECT * FROM cats"
Result suppose to look like
<select>
<option>cat_name</option>
<option>--cat_name_l1</option>
<option>--cat_name_l1</option>
<option>----cat_name_l2</option>
<option>----cat_name_l2</option>
<option>cat_name</option>
</select>
Can You help me?
function _buildTree($data, $idParent, $indentSymbol, $level)
{
$cat = array();
foreach($data as $row){
if($row['parent_id'] == $idParent){
if($indentSymbol AND $level > 0){
$symbols = array_fill(0, $level, $indentSymbol);
$cat[$row['id']] = implode('', $symbols) . $row['name'];
}else{
$cat[$row['id']] = $row['name'];
}
$cat = $cat + _buildTree($data, $row['id'], $indentSymbol, $level++);
}
}
return $cat;
}
$result = mysql_query("SELECT * FROM cats");
$data = array();
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
$select = '<select>';
foreach(_buildTree($data, 0, '-', 0) as $key=>$option){
$select .= '<option value=' . $key . '>' . $option . '</option>';
}
$select .= '</select>';
Try this for generating the required dropdown:
$result=mysql_query("SELECT * FROM cats");
$opt='<select>';
while($row=mysql_fetch_array($result))
{
$cat[$row['id']][0]=$row['parent_id'];
$cat[$row['id']][1]=$row['name'];
}
foreach($cat as $ct)
{
$level=0;
$temp=$ct;
while($temp[0]!=0)
{
$temp=$cat[$temp[0]];
$level++;
}
$opt.="<option>";
for($i=0;$i<$level;$i++)
{
$opt.="--";
}
$opt.=$ct[1];
$opt.="</option>";
}
$opt.="</select>";
Then, you can use this as:
echo $opt;

Categories