PHP While wont return first row - php

got a problem with my while statement, it will not display the first row & I have no idea why, any help would be appreciated.
<?php
$user = $_SESSION['username'];
$result = mysql_query("SELECT *FROM bookwrite WHERE username = '$user' ", $connection);
if (mysql_fetch_array($result)==0){
$class = "hideMe";
$firstnameResult = mysql_query("SELECT * FROM users WHERE username = '$user' ", $connection);
$row2 = mysql_fetch_array($firstnameResult);
echo "<div class=\"platOptions welcome\"><div class=\"welcomeinfo\"><h1>Welcome!</h1>Welcome to Little Quill, ".$row2["firstName"].". We see you are new to the platform. To get started by adding your first post please click the \"New Entry\" button below <a class=\"newentryBTN\" href=\"newEntry.php\">New Entry</a></div></div>";
} else {
$class = "";
while ($row = mysql_fetch_array($result)) {
echo nl2br("<li class=\"editable\" id=\"".$row["id"]."\">"."<div class=\"entryInfo clearfix\">"."<div class=\"statusWrapper\"><div class=\"status\"></div><div class=\"statusIcon\"></div></div>"."<h1>".$row["post_title"]."</h1>"."<div class=\"timeline-date entryDate\">".$row["post_date"]."</div>"."</div>"."<p contentEditable=\"true\">".$row["post_details"])."</p><a class=\"deleteBTN\"href='delete.php?id=".$row["id"]."'>x</a></li>";
}
}
?>

The first result is consumed by mysql_fetch_array, so when you start your loop you are consuming the second item. Try this code out, I basically assign the next value, at the end of the loop.
Also, I 100% agree with Jason McCreary, and I will make the comment that your current query is subject to SQL Injection. However, this should solve your first problem, helping you take a baby step towards to solution that's ultimately correct.
<?php
$user = $_SESSION['username'];
$result = mysql_query("SELECT * FROM bookwrite WHERE username = '$user' ", $connection);
$bookwrite_row = mysql_fetch_array($result);
if($bookwrite_row) {
while($bookwrite_row) {
echo nl2br("<li class=\"editable\" id=\"".$row["id"]."\">"."<div class=\"entryInfo clearfix\">"."<div class=\"statusWrapper\"><div class=\"status\"></div><div class=\"statusIcon\"></div></div>"."<h1>".$row["post_title"]."</h1>"."<div class=\"timeline-date entryDate\">".$row["post_date"]."</div>"."</div>"."<p contentEditable=\"true\">".$row["post_details"])."</p><a class=\"deleteBTN\"href='delete.php?id=".$row["id"]."'>x</a></li>";
$bookwrite_row = mysql_fetch_array($result);
}
} else {
$class = "hideMe";
$firstnameResult = mysql_query("SELECT * FROM users WHERE username = '$user' ", $connection);
$row2 = mysql_fetch_array($firstnameResult);
echo "<div class=\"platOptions welcome\"><div class=\"welcomeinfo\"><h1>Welcome!</h1>Welcome to Little Quill, ".$row2["firstName"].". We see you are new to the platform. To get started by adding your first post please click the \"New Entry\" button below <a class=\"newentryBTN\" href=\"newEntry.php\">New Entry</a></div></div>";
}

if (mysql_num_rows($result)==0){
$class = "hideMe";
...

Related

Passing php variables through pages / sql

i have the following information displayed
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0)
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
?>
as you can see i have created a game_details page which will display that specific Game_id when the image is clicked
im having trouble understanding how to pull the data out from that game_id in sql on the other page.
here is my attempt on the game_details page
<?php
if (!isset($_GET['$game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id={$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['$game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
This attempt is giving me the "invalid category ID" error
Would appreciate help
There are a few issues with your code.
Let's start from the top.
['$game_id'] you need to remove the dollar sign from it in $_GET['$game_id']
Then, $row['$game_id'] same thing; remove the dollar sign.
Then, game_id={$game_id}' will throw a syntax error.
In your first body of code; you should also use proper bracing for all your conditional statements.
This one has none if (mysqli_num_rows($result) > 0) and will cause potential havoc.
Rewrites:
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0){
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
}
?>
Sidenote for WHERE game_id='{$game_id}' in below. If that doesn't work, remove the quotes from it.
WHERE game_id={$game_id}
2nd body:
<?php
if (!isset($_GET['game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id='{$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
Use error checking tools at your disposal during testing:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
You want to be using $_GET['gameid'] as that's the parameter you passed.
You are calling for game_id when the link to go to game_details.php has the variable gameid. Either change the parameter in the link to game_id or call for gameid in your $_GET['$game_id'].
Also, as Fred -ii- said, take out the dollar sign in $_GET['$game_id']

Disable updating data when database is empty

I am having a problem when I want to echo "The stock is less than what you want". The problem is the user still can update the cart when the stock in my database less that what the user wants. It should show an error "The stock is less than what you want".
This is my code.
<?php session_start();
require("config.php");
$user = $_SESSION['userlogin'];
$cek = mysql_query("SELECT * FROM transaksitbl WHERE username = '$user' AND status ='0'") or die(mysql_error());
$result = mysql_num_rows($cek);
$data = mysql_fetch_array($cek);
if ($result > 0)
{
$faktur =$data['notransaksi'];
for ($i=1; $i<=$_POST['n']; $i++)
{
$idp = $_POST['id'.$i];
$cari2 = mysql_query("SELECT * FROM barangtbl WHERE id='$idp'") or die(mysql_error());
$row2 = mysql_fetch_array($cari2);
$har = $row2['harga'];
$stock = $row2['stock'];
if($_POST['n'] <= $row2['stock'])
{
echo "The stock is less than what you want";
}
if ($cari2)
{
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
}
}
}
header ("location:shopping_cart.php");
?>
If i understood you properly the
if($cari2){}
function is executing?
All you are checking there is if the $cari2 variable is true.
Simply make a else statement out of the if($cari2){} statement so that if the stock is less than you wan't the second if statement won't get executed.
So, like this:
if($_POST['n'] <= $row2['stock']){
echo "The stock is less than you want";
}
else {
if($scari2){
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
} else {
die('Woop, there seems to be a problem with the $scari2 variable. The value is:' . $scari2);
} // END OF INNER ELSE
} // END OF ELSE
And one more thing NEVER forget to use the mysql_real_escape_string() function on a variable before submiting it's value to the database.

how can i display sql query in php? CLOSED

<?php
include 'config.php'; //connect to db
if(isset($_REQUEST["pwd"]) && isset($_REQUEST["name"])) {
$password = $_REQUEST['pwd']; //pass from previous page
$name = $_REQUEST['name']; //pass from previous page
$checkUserPass = mysql_query("SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //check if the user exist
if(mysql_num_rows($checkUserPass) == 1) {
$personnelId = mysql_query("SELECT PersonnelID FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //query user id
while($row = mysql_fetch_assoc($personnelId)) {
echo $row['PersonnelD']; // print user id
}
mysql_close($conn);
//echo "<br/><br/>";
//echo "<script>alert('Logged In.')</script>";
//header("Refresh: 1; url=profile/profile.php?id="'.$id.');
//header('Refresh: 1; url=test.php?id=$personnelId');
} else {
echo "<br/><br/>";
echo "<script>alert('Wrong Password.')</script>";
header('Refresh: 1; url=personnelselect.php');
}
}
?>
i cannot echo the $row['PersonnelD'] the page shows blank. i cannot understand where did i go wrong. this page quesion have been solved
Looks like you have mistake in code:
echo $row['PersonnelD'];
shouldn't it be following?
echo $row['PersonnelID'];
check the mysql_fetch_assoc() function may be its parameter is empty so it can't enter the while loop
Try to debug and check the values came in the variables using var_dump() function. Ex: var_dump($row); in while loop.
In both your querys, you have
"SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'"
It should be:
"SELECT * FROM validPersonnel WHERE Passkey = '".$password."' and Name = '".$name."';"
PHP doesn't recognize the $var unless you close the quotes. The period adds the $var to the string.

Mysql Array Not Working

I am trying to echo out all of the user rows in my database as a select in a form.
It is only showing a blank space. Nothing else.
Here is my code.
<?php
session_start();
require('../../config.php');
$user = $_SESSION['user'];
$qry=("SELECT `rank`, `uname` FROM users WHERE `uname` = '$user'");
$result=mysql_query($qry);
$row = mysql_fetch_assoc($result);
$rank = $row['rank'];
$logged = $_SESSION['loggedin'];
if ($logged == true) {
if ($rank >= 3) {
echo "Succesful, $user.<br />
<form method='POST' action='delete.php'>
<select><option>Please select</option>";
while ($row = mysql_fetch_assoc($result)) {
$users = $row['uname'];
$lol = ucwords($users);
}
echo "<option>$lol</option>";
echo "</select>
</form>";
} else {
echo "Your not an admin. $user";
}
} else {
echo "Please login.";
}
?>
First, please stop using mysql_ functions as they are being deprecated. Look into mysqli_ or PDO. Be aware that your script is vulnerable to SQL injection.
The reason your script is not working is because it appears you are calling mysql_fetch_assoc twice. When calling it the second time, there won't be any output if your query only returns a single row.
$qry=("SELECT `rank`, `uname` FROM users WHERE `uname` = '$user'");
$result=mysql_query($qry);
$row = mysql_fetch_assoc($result);
$rank = $row['rank'];
You will need to resubmit a query (something like below) and call that result separately to populate the drop down, or store the result in an array.
$qry=("SELECT `uname` FROM users");
$result=mysql_query($qry);
while ($row = mysql_fetch_assoc($result)) {
echo '<option>' . ucwords($row['uname']) . '</option>';
}
It looks like your while loop is set up badly, I think you need to change
while ($row = mysql_fetch_assoc($result)) {
$users = $row['uname'];
$lol = ucwords($users);
}
echo "<option>$lol</option>";
to this
while ($row = mysql_fetch_assoc($result)) {
$users = $row['uname'];
$lol = ucwords($users);
echo "<option>$lol</option>";
}
UPDATE:
I reread your question and it seems that you want to display all unames from your table.
The original query was to check if the user is an admin.
Here's how it will look like. But it's just a duplicate of njk's answer.
<?php
session_start();
require('../../config.php');
$user = $_SESSION['user'];
$qry=("SELECT `rank`, `uname` FROM users WHERE `uname` = '$user'");
$result=mysql_query($qry);
$row = mysql_fetch_assoc($result);
$rank = $row['rank'];
$logged = $_SESSION['loggedin'];
if ($logged == true) {
if ($rank >= 3) {
echo "Succesful, $user.<br />
<form method='POST' action='delete.php'>
<select><option>Please select</option>";
// added these 2 lines
$qry=("SELECT `rank`, `uname` FROM users");
$result=mysql_query($qry);
while ($row = mysql_fetch_assoc($result)) {
$users = $row['uname'];
$lol = ucwords($users);
echo "<option>$lol</option>";
}
echo "</select>
</form>";
} else {
echo "Your not an admin. $user";
}
} else {
echo "Please login.";
}
?>
Are you sure your database has more than 1 row? You are calling the fetch 1 time so the second time it will try to fetch the second row.
Try also running the query directly into mysql and see if you get the rows you're expecting back, may be its not returning what you expected

MySQL Rows not Displayed [duplicate]

I am trying to echo out all of the user rows in my database as a select in a form.
It is only showing a blank space. Nothing else.
Here is my code.
<?php
session_start();
require('../../config.php');
$user = $_SESSION['user'];
$qry=("SELECT `rank`, `uname` FROM users WHERE `uname` = '$user'");
$result=mysql_query($qry);
$row = mysql_fetch_assoc($result);
$rank = $row['rank'];
$logged = $_SESSION['loggedin'];
if ($logged == true) {
if ($rank >= 3) {
echo "Succesful, $user.<br />
<form method='POST' action='delete.php'>
<select><option>Please select</option>";
while ($row = mysql_fetch_assoc($result)) {
$users = $row['uname'];
$lol = ucwords($users);
}
echo "<option>$lol</option>";
echo "</select>
</form>";
} else {
echo "Your not an admin. $user";
}
} else {
echo "Please login.";
}
?>
First, please stop using mysql_ functions as they are being deprecated. Look into mysqli_ or PDO. Be aware that your script is vulnerable to SQL injection.
The reason your script is not working is because it appears you are calling mysql_fetch_assoc twice. When calling it the second time, there won't be any output if your query only returns a single row.
$qry=("SELECT `rank`, `uname` FROM users WHERE `uname` = '$user'");
$result=mysql_query($qry);
$row = mysql_fetch_assoc($result);
$rank = $row['rank'];
You will need to resubmit a query (something like below) and call that result separately to populate the drop down, or store the result in an array.
$qry=("SELECT `uname` FROM users");
$result=mysql_query($qry);
while ($row = mysql_fetch_assoc($result)) {
echo '<option>' . ucwords($row['uname']) . '</option>';
}
It looks like your while loop is set up badly, I think you need to change
while ($row = mysql_fetch_assoc($result)) {
$users = $row['uname'];
$lol = ucwords($users);
}
echo "<option>$lol</option>";
to this
while ($row = mysql_fetch_assoc($result)) {
$users = $row['uname'];
$lol = ucwords($users);
echo "<option>$lol</option>";
}
UPDATE:
I reread your question and it seems that you want to display all unames from your table.
The original query was to check if the user is an admin.
Here's how it will look like. But it's just a duplicate of njk's answer.
<?php
session_start();
require('../../config.php');
$user = $_SESSION['user'];
$qry=("SELECT `rank`, `uname` FROM users WHERE `uname` = '$user'");
$result=mysql_query($qry);
$row = mysql_fetch_assoc($result);
$rank = $row['rank'];
$logged = $_SESSION['loggedin'];
if ($logged == true) {
if ($rank >= 3) {
echo "Succesful, $user.<br />
<form method='POST' action='delete.php'>
<select><option>Please select</option>";
// added these 2 lines
$qry=("SELECT `rank`, `uname` FROM users");
$result=mysql_query($qry);
while ($row = mysql_fetch_assoc($result)) {
$users = $row['uname'];
$lol = ucwords($users);
echo "<option>$lol</option>";
}
echo "</select>
</form>";
} else {
echo "Your not an admin. $user";
}
} else {
echo "Please login.";
}
?>
Are you sure your database has more than 1 row? You are calling the fetch 1 time so the second time it will try to fetch the second row.
Try also running the query directly into mysql and see if you get the rows you're expecting back, may be its not returning what you expected

Categories