Why I get only one row printed from my sql? - php

There is two rows that should be printed from my sql.
id Symbol Shares
3 CSCO 40
3 FB 200
but this code prints only first row twice. Like this:
jharvard has 40 shares of CSCOjharvard has 40 shares of CSCO
Why?
Thanky you in an advance.
$users = query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]);
$rows = query("SELECT * FROM stocks WHERE id = ?", $_SESSION["id"]);
$stock = $rows[0];
$username = $users[0];
foreach ($rows as $row)
{
if( $stock["id"] === $_SESSION["id"])
{
print("<td>" . $username["username"] . " has " . $stock["Shares"] . " shares of " . $stock["Symbol"] . "</td>");
}
}

The reason is your variables inside the loop
foreach ($rows as $row) {
if( $stock["id"] === $_SESSION["id"]) {
print("<td>" . $username["username"] . " has " . $stock["Shares"] . " shares of " . $stock["Symbol"] . "</td>");
}
}
You are printing the value of $stock, which earlier you defined:
$stock = $row[0];
So it will always output the data from the first row.
I suspect you want to change your loop as follows:
foreach ($rows as $row) {
// Changed from $stock['id'] to $row['id']
if( $row["id"] === $_SESSION["id"]) {
// Changed from $stock['Shares'] and ['Symbol'] to $row['Shares'] and ['Symbol']
print("<td>" . $username["username"] . " has " . $row["Shares"] . " shares of " . $row["Symbol"] . "</td>");
}
}

Related

Check if MySQL Column is empty

I'm working on a page, where users post their betting picks. In MySQL I have the table bets (id, event, pick, odds, stake, analysis, status, profit).
I would like to check if 'status' is empty in MySQL, but the if() statement is not working. If it's empty, it should output all the bets from a user. The code posted is in a for loop.
So what is wrong with the if() statement? And is there any better way to do this?
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
$row = mysqli_fetch_array($result);
if ('' !== $row['status']) {
echo "Status: " . $status . "</div>" .
"Published by: " . $user . "<br>" .
"PICK: " . $pick . "<br>" .
"Odds: " . $odds . "<br>" .
"Stake: " . $stake . "<br>" .
nl2br($analysis) ;
}
You are using identical comparison, which would check for type & value both. === or !== as this involves comparing the type as well as the value.
Instead try -
if (!empty($row['status'])) { // assuming status would hold only strings (not false/0 etc)
Or
if ($row['status'] != '') {
Use mysqli_num_rows(). If its greater then 0 then we can say that query containing result so we can further proceed.
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_array($result);
if ($row['status'] != "") {
echo "Status: " . $status . "</div>" .
"Published by: " . $user . "<br>" .
"PICK: " . $pick . "<br>" .
"Odds: " . $odds . "<br>" .
"Stake: " . $stake . "<br>" .
nl2br($analysis) ;
}
}
For status check you can use any of below method
if ($row['status'] != "") { }
OR
if (!empty($row['status'])) { }
If it's empty, it should output all the bets from a user. The code posted is in a for loop.
Since you are checking if it's empty, your if statement should be the other way round:
if ($row['status'] == '') {
Alternatively, you can use mysqli_num_rows() get the number of rows:
Returns the number of rows in the result set.
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
echo "Status: " . $status . "</div>" .
"Published by: " . $user . "<br>" .
"PICK: " . $pick . "<br>" .
"Odds: " . $odds . "<br>" .
"Stake: " . $stake . "<br>" .
nl2br($analysis) ;
}
Also, there isn't such function called queryMysql():
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
It should be mysqli_query(). For mysqli_query(), the connection parameter is needed.
$result = mysqli_query($conn, "SELECT * FROM bets WHERE user='$user'");

Warning: Invalid argument supplied for foreach() in /path/time/processing/time/viewpunlist.php on line 54

I am trying to get this php code to run. I have made it output the table, however, I am getting this error:
Warning: Invalid argument supplied for foreach() in /path/time/processing/time/viewpunlist.php on line 54
I have been able to use the $row to get the values of it before and even reassigned it later to make sure that it wasn't only executing in WHILE. I have no clue what is going on there. Line 54 is the line:
foreach ( $row as $each)
Here is the file that I am using it in. Any help is appreciated on
a) how to make this file better and
b) getting the whole foreach statement working.
Thank you in advance!
<head>
<title>View My Punches</title>
<body bgcolor="#9966FF">
<link rel="icon" type="image/ico" href="http://example.com/time/favicon.ico"/>
</head>
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define('DB_NAME', 'name');
define('DB_USER', 'user');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'host');
$link = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($link->connect_errno > 0){
die('Could not connect: ' .connect_error());
}
$userid_value = $_POST['userid'];
$table = "tc_".$userid_value;
$checkusersql = "SELECT * FROM tc_users WHERE userid = '$userid_value'";
$usercheck = $link->query($checkusersql);
$punchessql = "SELECT * FROM $table ORDER BY id";
$result = $link->query($punchessql);
$unixtime = time() + 60*60;
$time_value = date("h:i:s A", $unixtime);
$date_value = date("m/d/Y", $unixtime);
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
echo "Punch Report for " . $userid_value . " | Generated at " . $time_value . " on " . $date_value;
echo "<p></p>";
if ($result->num_rows == 0) {
echo "<p></p>";
echo "No punches were found for " . $userid_value . ".";
}else{
echo "<table border=1>";
echo "<tr><th>Punch ID</th><th>Time</th><th>Punch Type</th><th>Group</th><th>Department</th><th>Notes</th></tr>";
while ($row = $result->fetch_array())
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['time'] . "</td><td>" . $row['punchtype'] . "</td><td>" . $row['groupname'] . "</td><td>" . $row['dept'] . "</td><td>" . $row['notes'] . "</td>";
}
echo "</table>";
}
}
$differs = array();
$inout = array();
$inarray = array();
$outarray = array();
$current = array('in'=>$inarray,'out'=>$outarray,'length'=>'');
foreach ( $row as $each)
{
if ( $each['punchtype'] == 'in' )
{
if ( empty($current['in']) )
{ $current['in'] = $each; }
}
else if ( $each['punchtype'] == 'out' )
{
if ( empty($current['out']) )
{ $current['out'] = $each; }
}
if (( !empty($current['in']) && !empty($current['out'])))
{
$in = new DateTime($current['in']);
$out = new DateTime($current['out']);
$current['length'] = $in->diff($out);
$inout[] = $current;
$stamp = $inout['length'];
$stampformat = $stamp->format('%s');
$stampint = intval($stampformat);
$stampintval = $stampint/3600;
echo $stampintval;
}
}
?>
&nbsp
&nbsp
<form method="GET" action="http://example.com/time/panel.php">
<input type="submit" value="Go Home">
</form>
You need to check if the argument passed through foreach is an array.
This can be done by using the function is_array()
if (is_array($variable)) {
foreach ($variable as $item) {
}
}
Unless I am missing something, which I do a lot, it seems to me that you've already iterated through your SQL results here,
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
echo "Punch Report for " . $userid_value . " | Generated at " . $time_value . " on " . $date_value;
echo "<p></p>";
if ($result->num_rows == 0) {
echo "<p></p>";
echo "No punches were found for " . $userid_value . ".";
}else{
echo "<table border=1>";
echo "<tr><th>Punch ID</th><th>Time</th><th>Punch Type</th><th>Group</th><th>Department</th><th>Notes</th></tr>";
while ($row = $result->fetch_array())
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['time'] . "</td><td>" . $row['punchtype'] . "</td><td>" . $row['groupname'] . "</td><td>" . $row['dept'] . "</td><td>" . $row['notes'] . "</td>";
}
echo "</table>";
}
}
which means that the data is no longer available because you are not using a prepared statement in order to reuse it. You should be able to run another query for the foreach.
$punchessql = "SELECT * FROM $table ORDER BY id";
$result = $link->query($punchessql);
$row = $result->fetch_array();
foreach ( $row as $each) {
//your existing code.
}

Output single result of a MySQL Query with PHP not working

My table 'viewlevels' has the following data (among other):
id |title
10 |Cenas
I'm running the SQL query:
SELECT title FROM viewlevels WHERE id=10
Which is returning "Cenas" as expected.
But using the following PHP script, I just get "texto= " , why?
$res = $db->query("SELECT title FROM viewlevels WHERE id=10");
$res->data_seek(0);
while ($row = $res->fetch_assoc()) {
echo " texto= " . $row['title'] . "\n";
};
To see both fields you have to echo those columns:
while ($row = $res->fetch_assoc()) {
echo " id= " . $row['id'] . "\n";
echo " texto= " . $row['title'] . "\n";
};
You don't need to use data_seek in this instance.
$res = $db->query("SELECT title FROM viewlevels WHERE id=10");
while ($row = $res->fetch_assoc()) {
echo " texto= " . $row['title'] . "\n";
}
Will work.

PHP / MySQL - Nested List by recommendations / IDs

We have on a social project a member database, which includes, which member recommended an other member. The fields of the database looks like this:
id | name | email | code | recruit_by
Now we want to print a nested list of the structure, who recommended whom on all deep levels.
We didn't get it running with the following code:
<?PHP
mysql_connect("www.mysqlserver.net", "database1", "password") or die(mysql_error());
mysql_select_db("project_db1") or die(mysql_error());
echo "<ul>";
$result = mysql_query("SELECT * FROM registration") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<li class=\"level0\">" . $row['id'] . " - " . $row['name'] . " - " . $row['email'] . " - " . $row['recruit_by'] . "</li>";
// 1. Level
$result2 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row['id']) or die(mysql_error());
while($row2 = mysql_fetch_array($result2))
{
echo "<li class=\"level1\">1. " . $row2['id'] . " - " . $row2['name'] . " - " . $row2['email'] . " - " . $row2['recruit_by'] . "</li>";
// 2. Level
$result3 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row2['id']) or die(mysql_error());
while($row3 = mysql_fetch_array($result3))
{
echo "<li class=\"level2\">2. " . $row3['id'] . " - " . $row3['name'] . " - " . $row3['email'] . " - " . $row3['recruit_by'] . "</li>";
// 3. Level
$result4 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row3['id']) or die(mysql_error());
while($row4 = mysql_fetch_array($result4))
{
echo "<li class=\"level3\">3. " . $row4['id'] . " - " . $row4['name'] . " - " . $row4['email'] . " - " . $row4['recruit_by'] . "</li>";
// 4. Level
$result5 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row4['id']) or die(mysql_error());
while($row5 = mysql_fetch_array($result5))
{
echo "<li class=\"level4\">4. " . $row5['id'] . " - " . $row5['name'] . " - " . $row5['email'] . " - " . $row5['recruit_by'] . "</li>";
}
}
}
}
}
echo "</ul>";
?>
Very similar to an answer i gave here:
MySQL best practice: SELECT children recursive as performant as possible?
Again not the best use case for MySQL but yeah....
Dont do so many queries, do one
"SELECT * FROM registration"
Go through the result to build this as a tree like...
// use a database query to get this member info, here a simplified version
$member = array();
$member[] = array('id' =>'2', 'recruit_by' =>'1');
$member[] = array('id' =>'3', 'recruit_by' =>'2');
$member[] = array('id' =>'4', 'recruit_by' =>'3');
$member[] = array('id' =>'9', 'recruit_by' =>'1');
//use php to build a array containing all the recruit-relationships as a tree
function buildtree($member) {
$ref = array();
foreach($member as $mem){
$member_id = $mem['id'];
$parent = $mem['recruit_by'];
if(!is_array($ref[$member_id])) $ref[$member_id] = array('id' => $member_id);
if(!is_array($ref[$parent])) $ref[$parent] = array('id' => $parent);
$ref[$parent]['child'][] = &$ref[$member_id];
}
return $ref;
}
$tree = buildtree($member);
/// use a recursive function to output the tree
function echotree($tree, $parent = 0) {
foreach ($tree as $t) {
if($parent){
echo "$parent recruited " . $t['id'] . '<br>';
}
if(is_array($t['child']) && !$parent){
echotree($t['child'],$t['id']);
}
}
}
echotree($tree);
will give you:
2 recruited 3
1 recruited 2
1 recruited 9
3 recruited 4
should not be too hard to put this in whatever layout you wish.

Output stops after a while loop, without using "or die()"

I know there is another question with the same topic, but that question involves the or die() statement. I have the same problem, but i'm not using a or die() statement on my while loop. The answer is probably pretty obvious, but i can't figure it out.
$Dates = "1";
$Select = $mysqli->query("SELECT * FROM ----");
while ($Dates != "") {
$Dates = $Select->fetch_assoc();
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");
$Vals = $Get->fetch_assoc();
if ($Vals != "") {
$TimeIn = $Vals["Time_In"];
$TimeIn2 = explode(":",$TimeIn);
$TotIn = ($TimeIn2[0]*60)+$TimeIn2[1];
$TimeOut = $Vals["Time_Out"];
$TimeOut2 = explode(":",$TimeOut);
$TotOut = ($TimeOut2[0]*60)+$TimeOut2[1];
$TotTime = ($TotOut - $TotIn)/60;
$TotalTime = floor($TotTime) . " Hours " . ($TotTime-floor($TotTime))*60 . " Minutes";
echo "<tr><td>" . str_replace("_","/",$Dates["Meeting_Date"]) . "</td><td>" . $TimeIn . "</td><td>" . $TimeOut . "</td><td>" . $TotalTime . "</td></tr>";
}
if ($Vals == "") {
echo "<tr><td>" . str_replace("_","/",$Dates["Meeting_Date"]) . "</td><td colspan='3' style='background-color: rgba(0,0,0,0.25)'>Did not Attend</td></tr>";
}
}
Anything i put after the while loop, doesn't get executed, even though the while loop only executes 2 times like it is supposed to...
Any ideas are appreciated
This is the problem:
while ($Dates != "") {
$Dates = $Select->fetch_assoc();
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");
When there are no more records, $Dates will be empty (NULL) so the next line will lead to a fatal error.
You can change it to:
while ($Dates = $Select->fetch_assoc()) {
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");

Categories