Trouble with updating table with arrays - php

After being stuck trying to get a grip of how this works, i've decided to ask for some hints to how I can do this.
Let me start by saying I have next to no experience with anything like this. I've just gathered some logic by looking at the code and i'm almost done with my project, except for this issue that i've come by.
This is the original code (which i am still using another place in the code, this appears to be working just fine).
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="kurv.php?action=update" method="post" id="cart">';
$output[] = '<table>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM varetabel WHERE varenr = '.$id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td>Slet</td>';
$output[] = '<td>'.$varenavn.'</td>';
$output[] = '<td>DKK '.$pris.'</td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '<td>DKK '.($pris * $qty).'</td>';
$total += $pris * $qty;
$output[] = '</tr>';
$_SESSION['items'] = $contents; // Antal forskellige varer.
$_SESSION['qty'] = $qty;
}
$output[] = '</table>';
$output[] = '<p>Pris total: <strong>DKK '.$total.'</strong></p>';
$output[] = '<div><button type="submit">Opdatér kurv</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>Kurven er tom.</p>';
}
return join('',$output);
}
global $db is connecting to the DB and such, no biggie, and then there is this function from an include:
function fetch () {
if ( $row=mysql_fetch_array($this->query,MYSQL_ASSOC) ) {
return $row;
} else if ( $this->size() > 0 ) {
mysql_data_seek($this->query,0);
return false;
} else {
return false;
}
}
Now, im trying to use the same method to take the arrays from this code and put them into my database with this code:
session_start();
global $db;
$items = $_SESSION['items'];
$cart = $_SESSION['cart'];
$qty = $_SESSION['qty'];
if(isset($_SESSION['email'])) { // IF LOGGED IN
$sql = mysql_query("SELECT * FROM antalstabel ORDER BY ordrenr DESC LIMIT 1") or die(mysql_error());
$row = mysql_fetch_assoc($sql);
$maxordrenr = $row['ordrenr'];
$nextnumber = $maxordrenr + 1;
$antal = count($items); // COUNTS DIFFERENT ITEMS IN CART.
$maxplusantal = $maxordrenr + $antal;
$varenrplaceholder = 0;
for ($i = $maxordrenr; $i <= $maxplusantal; $i++) {
$sql = mysql_query("INSERT INTO antalstabel (ordrenr, varenr) VALUES ('$nextnumber','$varenrplaceholder')") or die(mysql_error());
$nextnumber--;
$varenrplaceholder++;
}
$varenrplaceholder = 0;
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
foreach ($contents as $id=>$qty) {
$sql = 'UPDATE antalstabel SET varenr = '.$id.' and antal = '.$qty.' WHERE ordrenr = '.$nextnumber.' and varenr = '.$varenrplaceholder.'';
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$varenrplaceholder++;
}
}
But it does not appear to be working properly, the code does run, but it does not update the tabel with the values of the arrays.
Am i completely wrong or can anyone help me with this issue, i know it is a lot to ask.
my own code creates X rows with the same ID depending on how many different items there is in the cart, I am trying to update those existing rows that i've just created with the values i presume is still in the arrays of the showCart() function.
Thank you in advance

$sql = 'SELECT * FROM varetabel WHERE varenr = '.$id;
$result = $db->query($sql);
You aren't checking the success/failure status returned by query(). Most of the MySQL functions return false if there's an error, for example a misspelled table name or an invalid expression in the WHERE clause.
I don't know what $id is, but you should inspect the $sql string to see if it works (copy & paste it into a mysql client session to test it).
And you should always check that $result is not false. See http://php.net/mysql_error

there is error at your code line
foreach ($contents as $id=>$qty) {
$sql = 'UPDATE antalstabel SET varenr = '.$id.',antal = '.$qty.' WHERE ordrenr = '.$nextnumber.' and varenr = '.$varenrplaceholder.'';
$varenrplaceholder++;
}
$select_query='SELECT * FROM varetabel WHERE varenr = '.$id;
$result = $db->query($select_query);
$row = $result->fetch();
extract($row);

You appear to be creating a lot of dummy records, then going through an updating them. I would expect you to have just needed to do the insert, but wondering if this is something to do with the fetch you do after the update.
However the main thing that I suspect stops you query working is that you count the number of $items before you have set $items to the exploded $cart.
I have done the following, using assumed names for the methods in your db class
<?php
session_start();
global $db;
$items = $_SESSION['items'];
$cart = $_SESSION['cart'];
$qty = $_SESSION['qty'];
if(isset($_SESSION['email']))
{ // IF LOGGED IN
if ($cart)
{
$sql = "SELECT MAX(ordrenr) AS ordrenr FROM antalstabel";
$result = $db->query($sql) or die($db->error());
if ($row = $result->fetch())
{
$maxordrenr = $row['ordrenr'];
$nextnumber = $maxordrenr + 1;
$items = explode(',',$cart);
$antal = count($items); // COUNTS DIFFERENT ITEMS IN CART.
$maxplusantal = $maxordrenr + $antal;
$varenrplaceholder = 0;
for ($i = $maxordrenr; $i <= $maxplusantal; $i++)
{
$sql = "INSERT INTO antalstabel (ordrenr, varenr) VALUES ('$nextnumber','$varenrplaceholder')";
$db->query($sql) or die($db->error());
$varenrplaceholder++;
}
$varenrplaceholder = 0;
$contents = array();
foreach ($items as $item)
{
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
foreach ($contents as $id=>$qty)
{
$sql = "UPDATE antalstabel SET varenr = $id and antal = $qty WHERE ordrenr = $nextnumber and varenr = $varenrplaceholder";
$result = $db->query($sql) or die($db->error());
$row = $result->fetch();
extract($row);
$varenrplaceholder++;
}
}
}
}
?>

Related

Trying to insert array to database without getting repetition

My english is not the best so I will try my best apologize if confusing.Anyways I am making a game where everyone is assigned a role.The problem I have is everytime it inserts into the database there a repetitive not in the name but number when it comes to array[].
<?php
include_once('database.php');
$roles = array('cop','cop','robber','robber','gangster','gangster');
$array = array();
$sql = mysqli_query($db,"SELECT * FROM `account`");
$i=0;
while ($row = mysqli_fetch_assoc($sql)) {
$array[] = $row;
}
shuffle($roles);
for ($i=0; $i < count($array); $i++) {
$realrole = $roles[$i];
$name = $array[$i]['name'];
echo(" ".$realrole);
$sq = "UPDATE account SET role = '$realrole' WHERE name = '$name'";
}
mysqli_query($db,$sq);
I spent long hours on this and I am still new hope it make sense thank you
I think it should solve your issue
<?php
include_once('database.php');
$roles = array('cop','cop','robber','robber','gangster','gangster');
$array = array();
shuffle($roles);
$sql = mysqli_query($db,"SELECT * FROM `account`");
while ($row = mysqli_fetch_assoc($sql)) {
$array[] = $row;
}
$i=0;
for ($i=0; $i < count($array); $i++) {
$realrole = $roles[$i];
$name = $array[$i]['name'];
echo(" ".$realrole);
$sq = "UPDATE account SET role = '".$realrole."' WHERE name = '".$name."'";
mysqli_query($db,$sq);
}

Multiple Loops running together

$a_forms = array("a_GG", "a_FF");
$sql = "SELECT name, field FROM categories WHERE enabled = '1' ";
$result = mysqli_query($con,$sql);
$Others = array();
while($row = mysqli_fetch_array($result)) {
$Other_names[] = $row['name'];
$Other_fields[] = $row['db_field'];
}
for ($i=0;$i<count($a_forms);$i++) {
if ($a_forms[$i] == "a_FF") {
$dforms_sql = "SELECT *
FROM a_FF
where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while ($forms_row = mysqli_fetch_array($dforms_result)) {
for ($i=0; $i<count($Other_fields); $i++) {
echo "<tr><td colspan='3'>".$Other_names[$i]."</td></tr>";
}
}
} elseif ($a_forms[$i] == "a_GG") {
$dforms_sql = "SELECT *
FROM a_GG where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while($forms_row = mysqli_fetch_array($dforms_result)) {
echo 'Other cool stuff';
}
}
} //END (first) For Loop
So, for some reason, if that second for loop, $Other_field is there it will only show the IF statement for a_FF. But if the array = a_FF and a_GG and the for loop for $other_field is NOT there it displays them both. So it's obviously that for loop that is breaking something, I have no idea what though. Anyone have any thoughts?

$i not incrementing in while loop

Following is my PHP code which is only giving i =0 though in a loop I am incrementing the $i but it always return i as 0 and while loop is only working one time, though my query SELECT * FROM events WHERE DATE(event_date) < CURDATE() is returning 7 records when exectuing in phpmyadmin. Let me know what i am doing wrong here ?
Code -
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/app/'."config.php";
error_reporting(E_ALL);
if( $_POST['number'] == 'all' ) {
$eventArr = array();
$myarray = array();
$query = "SELECT * FROM events WHERE DATE(`event_date`) < CURDATE()";
$result = mysql_query($query);
$i =0;
while($row = mysql_fetch_assoc($result)) {
$eventArr[$i] = array('event_data'=> $row);
// Get image For an event
$event_id = $row['id'];
$query = "SELECT * FROM event_images WHERE event_id = $event_id ORDER BY `uploaded_date` DESC LIMIT 0,1";
$result = mysql_query($query);
$eventImgArr = array();
while($row = mysql_fetch_assoc($result)) {
$eventImgArr[] = $row;
}
$eventArr[$i]['event_image'] = $eventImgArr;
// Get venue details for the event
$venue_id = $row['venue_id'];
$eventVenArr = array();
$query = "SELECT * FROM `venues` WHERE id = $venue_id";
while($row = mysql_fetch_assoc($result)) {
$eventVenArr[] = $row;
}
$eventArr[$i]['venue_detail'] = $eventVenArr;
echo $i, " -- ";
$i++;
}
$myarray = array('response'=>'1','message'=>'Event data', 'data'=>$eventArr);
echo json_encode($myarray);
return;
}
You are re-using the $result variable for the other queries, which is destroying its value needed for the main loop.
P.S. Also, you're not actually executing the query for the venue details.

check table from my sql query

Hello I'm checking duplicated data from tables. I have a problem that from where data selected. My code is:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (".$select[$i].") WHERE location=('".$id."')";
$result = mysql_query($SQL);
$cs=$d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'],$sub_cat)) {
$sub_cat[]= $db_field['sub_cat'];
$cs++;
$d=$cs;
$d--;
}
}
}
I need to know that sub_cat selected from which $select[i]. How to find it?
To get the values, do this:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (" . $select[$i] . ") WHERE location=('".$id."')";
$result = mysql_query($SQL); // deprecated - use PDO
$cs = $d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'], $sub_cat)) {
$table = $select[$i];
$sub_cat[$table][] = $db_field['sub_cat'];
// I have no clue what's going on here in your example:
$cs++;
$d=$cs;
$d--;
}
}
}
}
Then, to retrieve it:
foreach ($sub_cat as $table_name => $values) {
foreach ($values as $row) {
// output values here
}
}

Dynamic Update MySql Table

I am attempting to Dynamically update a MySql table, the $query looks correct when i echo it, but for some reason it dose not work when i insert the code into the MySql Query.
$b = 1;
$query_a = array();
$vars = array();
$result = mysql_query("SELECT * FROM my_table");
for ($i = 0; $i < mysql_num_fields($result); $i++) {
$vars[] = mysql_field_name($result,$b);
$b++;
}
foreach ($vars as $v)
{
if (isset($_GET[$v]))
{
$isclean = $_GET[$v];
$query[] = $v.' = '.$isclean.'';
}
}
$query = implode(',', $query);
mysql_query("UPDATE my_table SET $query WHERE UIN = '1'");
Without knowing your data types, my guess is it's because you're not adding single quotes around your values. You probably want something like:
$query[] = $v.' = \''.$isclean.'\'';

Categories