Dynamic Update MySql Table - php

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.'\'';

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);
}

php and mysql issue with query return

I have this code working but only halfway, it is able to return all of the information that I need however on the return, one of the JSON array is returned twice, why is this? I can't seem to figure out why.
Here is my code:
$rows = mysql_num_rows($res);
$array = array();
$i = 0;
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$array[$i] = (int)$row[0] . "\n";
$i++;
if ($i > $rows){
break;
}
}
$JsonArray = array();
for($i = 0; $i < $rows; $i++){
$q = "SELECT firstName, lastName, email from $mysql_database.$UsersTable WHERE idUser = $array[$i]";
$res = mysql_query($q, $connect) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$new_array[] = $row; // Inside while loop
}
$JsonArray[$i] = $new_array;
}
echo json_encode($JsonArray);
This is the result:
All I need is the second and third but somehow I don't know why it is outputting the first twice.
Also, how can I format the result better in the JsonArray?
From what I see you are trying to do, you are trying to fetch your result set from the database for the query.
You need not make use of all those loops. All you have to do is:
$q = "SELECT firstName,lastName,email from $mysql_database.$UsersTable WHERE idUser=$array[$i]";
$res = mysql_query($q,$connect) or die(mysql_error());
$new_array = mysqli_fetch_assoc($res);
mysqli_free_result($res);
You do not need that while loop for each row.

Query outside while loop, for using inside loop, does'nt work

I have the following working code
$notchDetails = mysqli_query($conn, "SELECT * FROM notches WHERE projectid = ".$projectid." LIMIT ".$offset.", ".$limit."");
// i want $query here //
$outp3 = "[";
if (mysqli_num_rows($notchDetails) > 0) {
while($notch = mysqli_fetch_assoc($notchDetails)) {
$query = mysqli_query($conn, "DESCRIBE $table");
$count = count($notch);
$allnotches[] = $notch["notchid"]; // $allnotches is needed further in script //
if ($outp3 != "[") {$outp3 .= ",";}
$outp3 .= "{";
$x = 1;
while ($rs = mysqli_fetch_assoc($query)) {
$field = $rs["Field"];
$outp3 .= '"'.$field.'":"'.$notch[$field].'"';
if ($x != $count) { $outp3 .= ","; }
$x++;
}
$outp3 .= "}";
}
}
$outp3 .="]";
(Don't look at the var name notch, could'nt find a better translation than notch. Its complicated ;-) )
Problem explained:
When i place $query = mysqli_query...
outside the while loop (just under $notchDetails = mysqli_query...),
it only gives 1 result and the rest is left empty in: while ($rs = mysqli_fetch_assoc($query)) { //result// }
Af far as i can see, it should work with the $query above the loop. But i don't understand why it is'nt.
Can someone explain me why this does'nt work?
P.s. The reason for placing it outside the loop is performance/speed
mysqli_fetch_assoc is iterating through mysqli_result. When you have ended the iterating, you are not able to iterate it again. You can create a new query and iterate it.
So, when you put $query = mysqli_query($conn, "DESCRIBE $table"); outside the while loop, you are not creating a new query to iterate, so, after first iterating is completed, mysqli_fetch_assoc is not returning anything because you have no new queries, and old query is already iterated.
I would do something like:
$fields = [];
$table_structure = mysqli_query($conn, "DESCRIBE `notches`");
while ($row = $table_structure->fetch_assoc()) {
$fields[] = $row['Field'];
}
$notch_details = mysqli_prepare(
$conn,
'SELECT * FROM `notches` WHERE `projectid` = ? LIMIT ?, ?'
);
$notch_details->bind_param('iii', $projectid, $offset, $limit);
$notch_details->execute();
$notch_details = $notch_details->get_result();
$result = [];
while($notch = $notch_details->fetch_assoc()) {
$values = [];
foreach ($fields as $field) {
$values[$field] = $notch[$field];
}
$result[] = $values;
}
$result = json_encode($result);
As you can see, I have prepared a list of $fields once, and I use it later just as a list of fields, no need to query table description again and again.
Edit: Also, when you querying a database and fetching data as an associative array, you need no knowledge about table fields because you already have fields names in your result:
$notch_details = mysqli_prepare(
$conn,
'SELECT * FROM `notches` WHERE `projectid` = ? LIMIT ?, ?'
);
$notch_details->bind_param('iii', $projectid, $offset, $limit);
$notch_details->execute();
$notch_details = $notch_details->get_result();
$result = json_encode($notch_details->fetch_all(MYSQLI_ASSOC));
You will have the same result here without querying a table structure.

Mysql display all records

I need an SQL query that displays all the records if its duplicated also. For instance say
select * from table where true and p_id in(1,2,1,1)
displays only records from 1 and 2 but i need it to be repeated when given in while loop.
Update with code:
$cook = unserialize($_COOKIE["pro_cook"]);
foreach ($cook as $something) {
$merc[] = $something;
}
foreach ($size as $new_size) {
$size_array[] = $new_size;
}
$items = count($merc);
$mer = rtrim(implode(',', array_reverse($merc)), ',');
$fulclr = "and p_id in (".$mer.")";
$asd = "(p_id,".$mer.")";
$result = mysql_query("select * from product_details where true ".$fulclr." order by field".$asd."");
Hope this will help
$ids = "1,2,1,1";
$sql = "select * from table where true and p_id in (".$ids.")";
$rec = mysql_query($sql);
$dbData = array();
while($res = mysql_fetch_assoc($rec)) {
$dbData[$res['p_id']] = $res;
}
$ids = explode(',', $ids);
$newArray = array();
foreach ($ids as $id) {
if (!empty($dbData[$id])) {
$newArray[] = $dbData[$id];
}
}

Trouble with updating table with arrays

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++;
}
}
}
}
?>

Categories