Prepared statement returns same result during 'while' - php

I am trying to figure out why this while statement returns the same account ID each time. Below is the function I am using:
function Hourly(){
$sql = "SELECT * FROM users WHERE users.id IN(SELECT uid FROM point WHERE zoneid=1)";
$arr = array();
$user = $this->database->DBQry($sql, $arr);
$id = $user[0]['ID'];
$sql = "SELECT * FROM point WHERE zoneid > -1";
$arr = array();
$row = $this->database->DBCtr($sql, $arr);
$i=0;
while($i < $row){
$arr = array(":userid" => $id, ":zoneid" => 1, ":cash" => 500);
$this->database->DBIns($arr, 'cashtable');
echo"$id DONE!<br>";
$i++;
}
}
Here are my prepared statements I'm using.
// Query
function DBQry($sql,$arr){
$sth = $this->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($arr);
$rs = $sth->fetchAll();
return $rs;
}
// Count
function DBCtr($sql,$arr){
$sth = self::prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($arr);
return $sth->rowCount();
}
I think the issue I am encountering is with one of the statements.
What I am trying to achieve from the function is a result like this:
64 DONE!
80 DONE!
124 DONE!
648 DONE!
984 DONE!
1341 DONE!
1468 DONE!
1887 DONE!
2017 DONE!
2193 DONE!
2267 DONE!
But this is what comes out of the function:
64 DONE!
64 DONE!
64 DONE!
64 DONE!
64 DONE!
64 DONE!
64 DONE!
64 DONE!
64 DONE!
64 DONE!
64 DONE!
Code I am working from
<?
$DBHost = "localhost";
$DBUser = "user";
$DBPassword = "password";
$DBName = "db";
$Hcash=50;
$Link = MySQL_Connect($DBHost, $DBUser, $DBPassword) or die ("Can't connect to MySQL");
MySQL_Select_Db($DBName, $Link) or die ("Database ".$DBName." does not exist.");
$OnlineAccountQuery = Mysql_Query("SELECT * FROM point WHERE zoneid > -1");
$OnlineAccountNum = Mysql_Num_Rows($OnlineAccountQuery);
$i=0;
WHILE($i < $OnlineAccountNum){
$OnlineAccountArray = Mysql_Fetch_Array($OnlineAccountQuery);
$UID = $OnlineAccountArray['uid'];
MySQL_Query("INSERT INTO cashtable (userid, zoneid, cash) VALUES ($UID, 1, $Hcash)");
echo"$UID DONE!<br>";
$i++;
}
?>
Response to Shivan Raptor's Answer
function Hourly(){
$sql = "SELECT * FROM point WHERE zoneid > -1";
$arr = array();
$row = $this->database->DBCtr($sql, $arr);
$i=0;
while($i < $row){
$sql = "SELECT * FROM users WHERE users.id IN(SELECT uid FROM point WHERE zoneid=1)";
$arr = array();
$user = $this->database->DBQry($sql, $arr);
$id = $user[0]['ID'];
$arr = array(":userid" => $id, ":zoneid" => 1, ":cash" => 500);
$this->database->DBIns($arr, 'cashtable');
echo"$id DONE!<br>";
$i++;
}
}
Table Structures
CREATE TABLE `point` (
`uid` int(11) NOT NULL DEFAULT '0',
`aid` int(11) NOT NULL DEFAULT '0',
`time` int(11) NOT NULL DEFAULT '0',
`zoneid` int(11) DEFAULT '0',
`zonelocalid` int(11) DEFAULT '0',
`accountstart` datetime DEFAULT NULL,
`lastlogin` datetime DEFAULT NULL,
`enddate` datetime DEFAULT NULL,
PRIMARY KEY (`uid`,`aid`),
KEY `IX_point_aidzoneid` (`aid`,`zoneid`) USING BTREE
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `cashtable` (
`userid` int(11) NOT NULL,
`zoneid` int(11) NOT NULL,
`cash` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

You didn't overwrite $id. It's defined once before the while loop.
Please double check your logic.
UPDATE after question edit:
In your response's Hourly() function, $row should contain the count of rows of the first $sql. However, in the while loop, you're querying the 2nd same $sql again & again. Therefore, $id is always the same.
I think your 2nd query should relate to the result of first query, but you didn't. Consider joining 2 queries if possible.

Related

MYSQL: Insert variables into variable name table

I am trying to insert PHP variables in a mysql table, where the table name is also a variable, using mysqli_query. I've tried multiple solutions from stackoverflow but it still does not work.
I try to do it like this, maybe I am missing something. Thank you in advance!
<?php
session_start();
#include_once "modules/connections/dbconn.php";
$value = $_POST['value'];
$playerid = $_SESSION["steamid"];
$playername = fetchinfo("name","users","steamid",$playerid);
$playeravatar = fetchinfo("avatar","users","steamid",$playerid);
$playercoins = fetchinfo("coins", "users","steamid",$playerid);
if($playercoins - $value < 0){
die(json_encode(array('message' => 'ERROR', 'code' => "Not enough coins!")));
}
$game = fetchinfo("value","parameters","name","raffleRound");
$maxitems = fetchinfo("value","parameters","name","raffleMaxritems");
$items = fetchinfo("itemsnum","rafflegames","id",$game);
$itemname = "Coins";
$itemavatar = "images/creditcardicon.png";
$color = "D2D2D2";
$initialvalue = fetchinfo("value","rafflegames","id",$game);
$from = $initialvalue * 100;
$to = $from + $value * 100;
$tablename = 'rafflegame'.$game;
if($items < $maxitems){
mysqli_query($GLOBALS["connect"], "UPDATE rafflegames SET `value`=`value`+$value, `itemsnum`=`itemsnum`+1 WHERE `id`=$game");
mysqli_query($GLOBALS["connect"], "UPDATE users SET `coins`=`coins`-$value WHERE `steamid`=$playerid");
mysqli_query($GLOBALS["connect"], "INSERT INTO `" . $tablename . "` VALUES ('".$playerid."', '".$playername."','".$itemname."','".$color."','".$value."','".$playeravatar."','".$itemavatar."','".$from."','".$to."')");
}
else {
die(json_encode(array('message' => 'ERROR', 'code' => "Too many items in the current game")));
}
?>
The other two queries work just fine.
The table structure is this:
mysqli_query($GLOBALS['connect'],"CREATE TABLE `rafflegame$roundNumber` (
`id` int(11) NOT NULL auto_increment,
`userid` varchar(70) NOT NULL,
`username` varchar(70) NOT NULL,
`item` text,
`color` text,
`value` float,
`avatar` varchar(512) NOT NULL,
`image` text NOT NULL,
`from` int NOT NULL,
`to` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
mysqli_query($GLOBALS['connect'],"TRUNCATE TABLE `rafflegame$roundNumber`");
There is difference between table structure and insert column coumnt, When you want id column as auto incremented in that case column name should be included in insert query.
Please use the code as below:
<?php
session_start();
#include_once "modules/connections/dbconn.php";
$value = $_POST['value'];
$playerid = $_SESSION["steamid"];
$playername = fetchinfo("name","users","steamid",$playerid);
$playeravatar = fetchinfo("avatar","users","steamid",$playerid);
$playercoins = fetchinfo("coins", "users","steamid",$playerid);
if($playercoins - $value < 0){
die(json_encode(array('message' => 'ERROR', 'code' => "Not enough coins!")));
}
$game = fetchinfo("value","parameters","name","raffleRound");
$maxitems = fetchinfo("value","parameters","name","raffleMaxritems");
$items = fetchinfo("itemsnum","rafflegames","id",$game);
$itemname = "Coins";
$itemavatar = "images/creditcardicon.png";
$color = "D2D2D2";
$initialvalue = fetchinfo("value","rafflegames","id",$game);
$from = $initialvalue * 100;
$to = $from + $value * 100;
$tablename = 'rafflegame'.$game;
if($items < $maxitems){
mysqli_query($GLOBALS["connect"], "UPDATE rafflegames SET `value`=`value`+$value, `itemsnum`=`itemsnum`+1 WHERE `id`=$game");
mysqli_query($GLOBALS["connect"], "UPDATE users SET `coins`=`coins`-$value WHERE `steamid`=$playerid");
mysqli_query($GLOBALS["connect"], "INSERT INTO `" . $tablename . "`(`userid`,`username`,`item`,`color`,`value`,`avatar`,`image`,`from`,`to`) VALUES ('".$playerid."', '".$playername."','".$itemname."','".$color."','".$value."','".$playeravatar."','".$itemavatar."','".$from."','".$to."')");
}
else {
die(json_encode(array('message' => 'ERROR', 'code' => "Too many items in the current game")));
}
?>

Delete Row Result SQL Query

I am new in PHP. I am android developer and does not know PHP enough. I have developed one function which provide me numbers from MySQL database. I want delete that numbers instant as soon as it pass me. I am currently doing it like below
function getAllNumbers() {
require_once("includes/conf.php");
global $conn;
$sql = "SELECT number from number_list WHERE server=1";
$result = $conn->query($sql);
$data = array();
if($result) {
while($row = $result->fetch_row()) {
array_push($data, $row[0]);
$delete = "DELETE number from number_list WHERE server=1";
$result = $conn->query($delete);
}
}
$response["data"] = $data;
return $response;
}
My Table Structure is like below
id int(11) NO PRI NULL auto_increment
name varchar(50) NO NULL
number varchar(50) NO NULL
server int(10) NO 0
status int(1) NO -1
last_act timestamp NO CURRENT_TIMESTAMP
user_id int(11) NO MUL NULL
created_at timestamp NO CURRENT_TIMESTAMP
disable int(11) NO 0
notify int(1) NO 1
fcm varchar(500) NO NULL
But I am feeling that if there any new number arrive in database between number select query and delete query it will delete it without select number in first query. So I am looking to delete only rows which get selected in first query. Let me know if there anything I need to change in my codes.
Thanks a lot :)
So if you select the id in the first query as that is the unique key you can use that to delete just this row
function getAllNumbers() {
require_once("includes/conf.php");
global $conn;
$sql = "SELECT number,id from number_list WHERE server=1";
$result = $conn->query($sql);
$data = array();
if($result) {
while($row = $result->fetch_row()) {
$data[] = $row[0];
$id = $row[1];
$delete = "DELETE number from number_list WHERE id = $id";
$result = $conn->query($delete);
}
}
$response["data"] = $data;
return $response;
}

ON DUPLICATE KEY insertS new record instead of updating with Unique key

I have a issue, my INSERT ... ON DUPLICATE KEY UPDATE is inserting a new record instead of updating the row, the Table i am using has both an primary key and a unique key. So i am confused to why this is happening.
Table
CREATE TABLE `Product` (
`Product_Id` bigint(255) NOT NULL AUTO_INCREMENT,
`Resturant_ID` bigint(255) NOT NULL,
`Product_Desc` text NOT NULL,
`Product_Name` varchar(100) NOT NULL,
`Product_Price` decimal(8,0) NOT NULL,
`Add_On_ID` int(11) NOT NULL,
PRIMARY KEY (`Product_Id`),
UNIQUE KEY `Product_Name` (`Product_Name`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8
QUERY
$add_product_errors = array();
if (isset($_POST['add'])) {
$item_name = $_POST['item_name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
$rest_id = mysqli_real_escape_string($dbc, $_SESSION['Resturant_ID']);
if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) {
$add_product_errors['price'] = "Please enter a product price";
}
if (empty($_POST['item_name'])) {
$add_product_errors['item_name'] = "Please enter a name";
}
if (empty($_POST['desc'])) {
$add_product_errors['desc'] = "Please enter a product description";
}
$query = "INSERT INTO Product(Resturant_ID,Product_Name,Product_Desc,Product_Price) VALUES (?,?,?,?)
ON DUPLICATE KEY
UPDATE
Resturant_ID = VALUES(Resturant_ID)
,Product_Name = VALUES(Product_Name)
,Product_Desc = VALUES(Product_Desc)
,Product_Price = VALUES(Product_Price)";
$run_query = mysqli_prepare($dbc, $query);
if (!$run_query) {
die(mysqli_error($dbc));
}
mysqli_stmt_bind_param($run_query, 'sssd', $rest_id, $item_name, $desc, $price);
$execute = mysqli_stmt_execute($run_query);
$item_name = strip_tags($_POST['item_name']);
$desc = strip_tags($_POST['desc']);
//100 - changes the way the decimal displays in database
$price = strip_tags($_POST['price'] * 100);
if ($execute) {
echo "<script> alert('Addrrss Saved')</script>";
} else {
echo "<b>Oops! we have an issue </b>";
mysqli_stmt_close($run_query);
}
}
?>
The syntax just looks off to me. Maybe try writing the SQL and testing it first in console or MySQL workbench or whatever first? Try this:
$query = "INSERT INTO Product(Resturant_ID,Product_Name,Product_Desc,Product_Price) VALUES (?,?,?,?)
ON DUPLICATE KEY UPDATE
Resturant_ID = ?
,Product_Name = ?
,Product_Desc = ?
,Product_Price = ?";
$run_query = mysqli_prepare($dbc, $query);
if (!$run_query) {
die(mysqli_error($dbc));
}
mysqli_stmt_bind_param($run_query, 'issdissd', $rest_id, $item_name, $desc, $price, $rest_id, $item_name, $desc, $price);
Or maybe ? eight times and binding things twice... not sure off hand if mysqli supports named parameters...
Updated [again] per Martin's feedback.

PHP & MySQL array question

I'm trying to add the articles id to the title, summary and content but I don't know how to do it can some one help me solve this problem.
Here is the code that is giving me the problem.
while($row = mysqli_fetch_assoc($run)) {
$id[] = $row['id'];
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
}
And here is my PHP and MySQL code in full below.
$x = 0;
$con = null;
$search = $_REQUEST['search'];
$id = array();
$title = array();
$summary = array();
$content = array();
$search_explode = mysqli_real_escape_string($dbc, $search);
$search_explode = explode(' ', $search_explode);
foreach($search_explode as $search_each) {
$x++;
if($x == 1){
$con .= " article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
} else {
$con .= " OR article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
}
}
$con = "SELECT users.*, users_articles.* FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE ($con)
AND users.active IS NULL
AND users.deletion = 0";
$run = mysqli_query($dbc, $con);
$search_term = mysqli_num_rows($run);
while($row = mysqli_fetch_assoc($run)) {
$id[] = $row['id'];
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
}
while($row = mysqli_fetch_assoc($run)) {
// $id[] = $row['id']; you probably do not need this anymore
$title[$row['id']] = $row['title'];
$summary[$row['id']] = $row['summary'];
$content[$row['id']] = $row['article_content'];
}
// at this point, each array will contain rows
// with keys matching the corresponding id
var_dump($title);
var_dump($summary);
var_dump($content);
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
mysqli_fetch_assoc will fetch an associated array. Accessing the data directly like so $row['summary'] should fix your problem.
EDIT
Are you talking about string concatenation?
$title[] = $row['id'] . ' ' . $row['title'];
$summary[] = $row['id'] . ' ' . $row['summary'];
$content[] = $row['id'] . ' ' . $row['article_content'];
The above code will basically append the title/summary/content to your article ID and add it into respective arrays.
I am not sure what you want to achieve but I would suggest the the following solution. Please take a look.
CREATE TABLE IF NOT EXISTS users (
user_id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
deletion int(11) NOT NULL DEFAULT '0',
active int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table users
INSERT INTO users (user_id, name, deletion, active) VALUES
(1, 'John', 0, 1),
(2, 'George', 0, 1);
--
-- Table structure for table users_articles
CREATE TABLE IF NOT EXISTS users_articles (
id int(11) NOT NULL AUTO_INCREMENT,
user_id int(11) NOT NULL,
article_content varchar(255) NOT NULL,
title varchar(255) NOT NULL,
summary text NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table users_articles
INSERT INTO users_articles (id, user_id, article_content, title, summary) VALUES
(1, 1, 'test', 'test', 'test test test test'),
(2, 2, 'test 2', 'test 2', 'test test'),
(3, 1, 'test 3', 'test 3 ', 'test test test test 3'),
(4, 2, 'test 3', 'test 3', 'test test 3');
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysqli = new mysqli("localhost", "root", "", "articles");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Select queries return a resultset */
$con = 1;
$sql = "SELECT users.*, users_articles.* FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE ($con)
AND users.active = 1
AND users.deletion = 0";
$results = array();
if ($result = $mysqli->query($sql)) {
printf("Select returned %d rows.\n", $result->num_rows);
print '<pre>';
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
print_r($results);
print '</pre>';
/* free result set */
$result->close();
}
$mysqli->close();
?>
and when you will iterate $results you can concatenate id and other fields in that case you can utilize the result array in other areas too.

foreach function to create array from mysql db

need to return an array like this for example:
array(30 => 'Mercedes Benz 310 ',26 => 'Lamborghini Murcielago')
I have a database set up something like this:
CREATE TABLE cars (
id bigint(20) NOT NULL auto_increment,
`car_name` tinyint(2) NOT NULL default '0',
owner varchar(20) NOT NULL default ''
PRIMARY KEY (id)
) ENGINE=MyISAM;
The id need to be the array key.
So I tried to use foreach, but I have still not quite understood how it works.
$q = "select `id`, `car_name` from `cars` where `owner`='$username'";
$result = $conn->query($q);
unset($q);
if( !$result){
return array(0 => 'error');
}
$garage = $result->fetch_assoc();
$car_id = $garage["id"];
$car_name = $garage["car_name"];
foreach( $car_name as $key => $car_id ){
...
}
You aren't far off. Something like this should give you the kind of array you're looking for.
$q = "select `id`, `car_name` from `cars` where `owner`='$username'";
$result = $conn->query($q);
unset($q);
if( !$result){
return array(0 => 'error');
}
while($row = mysql_fetch_array($result)){
$garage[$row['id']] = $row['car_name'];
}
return $garage;

Categories