PHP not displaying result from MYSQL query - php

I have the following code
$sql = "SET #uid := (SELECT ID FROM channels WHERE Used = 0 ORDER BY RAND() LIMIT 1);";
$sql = "UPDATE channels SET Used = 1 WHERE ID = #uid;";
$sql = "SELECT * FROM channels WHERE ID IN = #uid;";
$result = mysqli_multi_query($conn, $sql)
or die( mysqli_error($sql) );
if (mysqli_num_rows($result) > 0) {
$text = '';
while($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
$text = $text . $Channel_Location;
}
}
Now the issue i'm having is the php isnt displaying the result returned by the MYSQL query which is stored in a session later on in the code to be displayed on a dummy page it comes up with the following error
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result
The my SQL query does exactly what I need it to I just need to, so I don't really want to change it. I just need some advice on how i'd get the PHP to echo the #uid
is there anyone willing to help me solve the issue? if so thankyou.

You have 3 queries in your $sql so you should use multi_query function
http://php.net/manual/en/mysqli.multi-query.php
And you can change your first query to:
SET #uid = 0;
SELECT #uid := ID FROM channels WHERE Used = 0 ORDER BY RAND() LIMIT 1);
Update You can try this fragment of your code modified with all commented improvements.
$sql = 'SET #uid = 0;';
$sql .= 'SELECT #uid:= ID FROM channels WHERE Used = 0 ORDER BY RAND() LIMIT 1);';
$sql .= 'UPDATE channels SET Used = 1 WHERE ID = #uid;';
$sql .= 'SELECT * FROM channels WHERE ID IN = #uid;';
if (mysqli_multi_query($conn, $sql)) {
do {
$result = mysqli_store_result($conn);
} while(mysqli_next_result($conn));
if (mysqli_num_rows($result) > 0) {
$text = '';
while($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
$text = $text . $Channel_Location;
}
}
} else {
die( mysqli_error($conn) );
}

Related

Get All Rows When Variable Empty PHP Mysql

$frame_type = '';
$ret = mysqli_query($con, "select * from products where status='1' AND frame_type = '$frame_type' ");
while ($row = mysqli_fetch_array($ret)) {
$emparray[] = $row;
}
Get All Rows If The $frame_type Is Empty I am trying this way but i get zero rows , How to fix that Where $frame_type has value then send to query else not
There are a some of things that is wrong with your question (code). But if you only want answer. Just copy this
$frame_type = '';
$query = "select * from products where status='1' ";
// strlen has value
if(strlen($frame_type)) {
$query .= "AND frame_type = '$frame_type'";
}
$ret = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($ret)) {
$emparray[] = $row;
}
PS: It's never a safe idea to pass everything to the query. Use prepared statement if you can.

Dynamic SQL statement based on foreach

How would I get this to work, because I am just getting errors right now.
$_GET['providers'] is an array of DB column names, which I am checking if = 1 in the below query.
foreach ($_GET['providers'] as $providers) {
$statement = "AND ".$providers."= '1' ";
}
$sql = "select * from users where user_id ='1' ".$statement." ";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
You should use a whitelist to check if the $providers are known column names. You then should concatenate the $statement, otherwise you overwrite that variable on every iteration.
$statement = '';
$columns = array('known', 'columns', 'go', 'here');
foreach ($_GET['providers'] as $providers) {
if(in_array($providers, $columns)) {
$statement .= " AND $providers = 1 ";
}
}
$sql = "select user_id from users where user_id =1 $statement limit 1";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
You also shouldn't use * unless you really want every column. If you just want to see if a row is returned you also can use limit 1 because you don't care about other rows.
You are overwriting $statement every time the loop is running.
$statement = "";
foreach ($_GET['providers'] as $providers) {
$statement .= "AND ".$providers."= '1' "; // note the ".=" to append
}
$sql = "select * from users where user_id ='1' ".$statement." ";
// to debug: echo "Query :: $sql";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}

why does my while loop stop after executed another query inside?closed

my while loop stops after executed another query inside... can you correct my codes? I want to update the column status in table ordered_items_supplier to "Pending" when the pi_number is found in the table purchased_items_supplier and if not found the column status is "Active".
$sql2 = "select * from ordered_items_supplier";
$result = $connect->query($sql2);
if($result->num_rows > 0){
while ($row = $result->fetch_assoc()) {
$pi_number = $row['pi_number'];
$sql = "select * from purchased_items_supplier where pi_number = '$pi_number'";
$result = $connect->query($sql);
if($result->num_rows > 0){
while ($row2 = $result->fetch_assoc()) {
$pi_number = $row2['pi_number'];
$sql = "update ordered_items_supplier set status = 'Pending' where pi_number = '$pi_number'";
$query = $connect->query($sql);
}
}else{
$sql = "update ordered_items_supplier set status = 'Delivered' where pi_number = '$pi_number'";
$query = $connect->query($sql);
}
}
}
here's my mysql.. it should update the status "Delivered" in ID 11
The problem is overwriting the same variable each time.
Check that you use $result for the outer and inner query both.That's why the problem occur. So don't overwriting the $result variable.

Update rows of a SQL table

I have a table with a column called 'status'. The defaut value of 'status' is 0. I want to update the value to '1' after using it.
I basically want to check if the status is 0, if it is, do an operation and then change the value to 1.
Here is the code. All works perfectly except that the value of 0 is not changed to 1.
I am a novice so maybe is a very basic mistake :(
<?php
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$sql = "UPDATE summonerid SET status='1' WHERE status='0';"; // THIS IS THE PART THAT DOES NOT WORK WELL
}
}
}
?>
Any help would be highly appreciated
Try this.. you are not executing the sql statements
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$result1 = $conn->query($sql);
$sql = "UPDATE summonerid SET status='1' WHERE status='0';";
$result1 = $conn->query($sql);
}
}
}
?>

Random row selection using MySQL returns NULL

I am trying to get a random row from MySQL table but all three attemps:
$query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
$query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
give a NULL result in mysql_query($query).
Higher up my PHP code I obtain a row from the same table OK by specifying WHERE, so I don't understand why I can't retrieve a random one.
Here is the code snippet:
$query = "SELECT uid,clu FROM uable WHERE un = '$un'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$resultid = mysql_fetch_assoc($result);
$uid = $resultid['uid'];
file_put_contents('debugging.txt',__LINE__.' - $uid = '.var_export($uid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE uid = $uid AND cn = '$cn'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$cr = mysql_fetch_assoc($result);
$cid= $cr['cid'];
file_put_contents('debugging.txt',__LINE__.' - $cid= '.var_export($cid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM fable WHERE cid= '$cid'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
file_put_contents('debugging.txt',__LINE__.' - $result = '.var_export($result,true).PHP_EOL,FILE_APPEND);
$fr = mysql_fetch_assoc($result);
file_put_contents('debugging.txt',__LINE__.' - $fr = '.var_export($fr,true).PHP_EOL,FILE_APPEND);
echo '<form action="'.$_SERVER['PHP_SELF'].’" method="post">';
if (!$fr) {
$o= $cn;
while ($o= $cn) {
// $ac = mysql_query("SELECT * FROM table") or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
// $num_rows = mysql_num_rows($ac);
//file_put_contents('debugging.txt',__LINE__.' - $num_rows = '.$num_rows.PHP_EOL,FILE_APPEND);
// --$num_rows;
// $query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
// $query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
$resultid = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($resultid);
$o= $opr['cn'];
}
file_put_contents('debugging.txt',__LINE__.' - $query = '.$query.PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $resultid = '.var_export($resultid,true).PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $op[\'cid\'] = '.$op['cid'].PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE cid= ".$op;
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($opr);
$o= $opr['cn'];
$od= $opr['description'];
echo '<p>'.$op;
if ($od<> '') {
echo ','.$odesc;
}
echo '</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
} else {
echo '<p>'.$fr['p'].'</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
}
echo '</form>';
The resulting debugging.txt:
24 - $uid = '4'
29 - $cid = '21'
32 - $result = NULL
34 - $fr = false
These queries look OK, but I think you're starting at the wrong place. When you're uncertain how to frame something in SQL, open up a SQL client like SequelPro or Navicat and try writing a few queries by hand until you get the result you want. (Also this gives you a chance to double-check the contents of relevant tables and ensure the expected data are there.) Then you can go back into the PHP with full confidence that the SQL code is correct, so if there's a problem it must be with the PHP (either the variables you inject into a Mysql statement, or the way you call that statement).

Categories