Trying to insert array to database without getting repetition - php

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

Related

data not gettinf inserted in mysql table

<?php
include 'dbh.php';
session_start();
if (isset($_GET['gmail'])) {
$gname = $_GET['gmail'];
}
$gname = mysqli_real_escape_string($connect, $gname);
$_SESSION['myusername'] = $gname;
$today = date("d.m.y");
$k=0;
$sql = "SELECT cart_fext FROM cart WHERE cart_sess = '$sess'";
$result=mysqli_query($connect, $sql);
$kode[$k] = array();
$kame[$k] = array();
$kesc[$k] = array();
$kail[$k] = array();
$kid[$k] = array();
$kate[$k] = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
extract($row);
$k = $k + 1;
$cname=$row['cart_item_name'];
$csize=$row['item_size'];
$cdesc=$row['cart_desc'];
$cfpath=$row['cart_fpath'];
$cfext=$row['cart_fext'];
$ccode=$row['cart_itemcode'];
$cuserid=$row['cart_usrid'];
$kode[$k] = $ccode;
$kame[$k] = $cname;
$kesc[$k] = $cdesc;
$kail[$k] = $gname;
$kid[$k] = $cuserid;
$kate[$k] = $today;
}
for($i=1; $i<=$k; $i++) {
$sqlsal = "INSERT INTO sales (s_code, s_name, s_desc, s_mail, s_userid, s_date) VALUES ('$kode[$i]', '$kame[$i]', '$kesc[$i]', '$kail[$i]', '$kid[$i]' ,'$kate[$i]')";
$result=mysqli_query($connect, $sqlsal);
}
header("location:makedir.php");
?>
my table sales is just not accepting data, dbh.php is to connect to the database
I don't understand what is wrong with this script?
please help?
I have checked your insert query it is running fine but I think the problem is with your SELECT query
SELECT cart_fext FROM cart WHERE cart_sess = '$sess'
please print the result of the query. I think that it may not be giving any result.

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.

$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.

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

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