While loop not printing all answers - php

This might be really simple, but i cannot figure out the problem with this code:
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
Now based on my database the query is returning 2 results, the echo mysql_num_rows($sql) also gives out 2. However the reached is echoed only once. Does anyone see a potential problem with the code?
P.S: My bad, $sql is being repeated, that was a silly mistake

It will only echo once because of this line :
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
your overwriting the $sql variable.
Why not just run a single query and join the data you require ?

try ($sql2 instead of $sql and $sql[0] to $sql2[0]):
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql2 = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql2[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}

I think it'll be because you are ressetting the sql variable
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
when you are still using it in the while loop. :P

It's probably this line:
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
Try using a different variable name.

You are changing the $sql variable inside the loop, therefore the next time you run $row = mysql_fetch_array($sql), the value will be different (probably won't be any based on your code).

Inside the while loop you are re-using the same variable: $sql. This is used to control the terminating condition of the loop.
Using a different variable name, e.g. $sql2 should leave the original variable intact and the loop should proceed as expected.

Related

deleting records from mysql table

Continuing with my simple CRUD, I'm stuck again...
So I have a table created called "usuaris" and a column called "id" which is my auto-increment and then another column called "usuari_nom". Now, I want to add "delete function", so when I am displaying the records of my table I've added a to delete it:
<div id="main">
<?php
global $conn;
$query = "SELECT * FROM usuaris";
if($grup_usuaris = mysqli_query($conn, $query)) {
echo "<table>";
echo "<tr><th>Usuaris</th><th>Accions</th></tr>";
while($row = mysqli_fetch_assoc($grup_usuaris)) {
echo "<tr><td>" . $row['usuari_nom'] . "</td><td>Eliminar usuari</td></tr>";
}
echo "</table>";
echo "+ Afegeix Usuari";
mysqli_free_result($grup_usuaris);
} else {
echo "query failed";
echo("Error description: " . mysqli_error($conn));
}
?>
</div>
So now, If I click on "eliminar usuari" it goes to the file where I am adding the query to delete, plus the id of that user; for example: "http://localhost/calendario/elimina_usuari.php?subject=6". But then, in the file elimina_usuari.php, how do I select the id to know what record to delete?
I've thought with $_GET but it doesn't seems to work, either with $_POST:
elimina_usuari.php
<?php
global $conn;
$usuari_id = $_GET['id'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
Any clue how can I get its id? Should I take it from the url somehow?
Thanks
you're doing fine.
just need to change this
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
as you're setting subject instead of id in your url
http://localhost/calendario/elimina_usuari.php?subject=6
^
and if you want to process id, like $_GET['id'], you need to change URL.
"http://localhost/calendario/elimina_usuari.php?id=6"
^ change here
EDIT
as per your comment,
you can use any $variable to $_POST or $_GET, it has nothing to do with the database column name.
Like you can use following.
"http://localhost/calendario/elimina_usuari.php?eve_mf=6"
and on elimina_usuari.php page,
$id = $_GET['eve_mf'];
and second part, why can I do that and I don't need to call it id as it is called in my db table?
Again, it's not the issue what you call variables in you local environment, all you to do(and should take care of) is to put right parameters in your sql query.
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
Here id is the name of your column name in your database. You can't change it here if you even want it to.
however, $usuari_id is your local variable, and you can change it whatever you want.
Hope I've explained what you're looking for :)
You can get the id with $_GET['subject'].
Please be aware about SQL injection as you are wrongly get the id of the user to be deleted:
$usuari_id = mysqli_real_escape_string($conn, $_GET['subject']);
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
You just need to Get the exact variable name or parameter name which you have sent with your url
I mean see your url contains subject=6
that means you have to get subject instead of id;
please replace this code
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
try this in elimina_usurai.php
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>

While loop within a while loop

I have one table which contains events and dates, and another which contains the guestlist for each of these nights. I can print the nights like so:
$day = date("l");
$date = getFullDateString($day);
$result = mysql_query("SELECT * FROM nights WHERE day = '$day' AND promoter = 'blah'") or die(mysql_error);
while ($row = mysql_fetch_array($result)) {
echo "<h2>";
echo $row[name];
echo " (";
echo getFullDateString($row[day]);
echo ")</h2>";
}
The problem is that for each of these events I want the guestlist to be printed below it. I've tried putting another while loop inside, but even the test echo doesn't work.
$result2 = mysql_query("SELECT DISTINCT guest FROM guestlists WHERE night = '$row[name]' AND date = 'getFullDateString($row[day])'") or die(mysql_error ());
while($row2 = mysql_fetch_array($result2)) {
echo $row2[0];
echo "test";
echo "<br />";
}
Essentially I want the following:
Event 1
Name 1
Name 2
Name 3
Event 2
Name 1
Name 2
Name 3
You have a method inside the query string which won't be run.
Try:
$sql = "SELECT DISTINCT guest FROM guestlists WHERE night = '".$row['name']."' AND `date` = '".getFullDateString($row['day'])."'"
Also, date is a reserved word in MySQL and should be encapsulated within backticks or changed to something else.
Additionally, the mysql_ functions are being deprecated and it is recommended to replace them with PDO or MySQLi.
Take a look at Complex (curly) syntax for string parsing to learn the proper way to embed your variables in the string.
Try this...
$result = mysql_query("SELECT * FROM nights WHERE day = '".$day."' AND promoter = 'blah'") or die(mysql_error);
while ($row = mysql_fetch_array($result)) {
echo "<h2>".$row[cname]."</h2>";
$result2 = mysql_query("SELECT DISTINCT guest FROM guestlists WHERE night = '$row[name]' AND date = '".getFullDateString($row[day])."'") or die(mysql_error);
while ($row2 = mysql_fetch_array($result2))
{
echo $row2[cname];
}
}

Loop through array, query each value until certain condition is met

I'm a bit of a newb to PHP and MySQL. I seem to be having an issue with something. How do I loop through an array, querying each value in the array until the query meets a certain condition.. In this case it would be that the number of rows returned from the query is less than five. Here is what I have:
$query1="SELECT UserID FROM Users where RefID='$userid'";
$result1=mysql_query($query1);
while ($row = mysql_fetch_array($result1, MYSQL_NUM) && $sql2querynum < '5')
{
echo ($row[0]);
echo "
";
$sql2 = "SELECT * FROM Users WHERE RefID=$row[0]";
$sql2result = mysql_query($sql2);
$sql2querynum = mysql_numrows($sql2result);
}
Problem is, for every value it echoes out, I get the following warning:
mysql_numrows(): supplied argument is not a valid MySQL result resource
Like I said, I'm a newb, so maybe I'm not even going about doing this the right way.
try this
$query1="SELECT UserID FROM Users where RefID='$userid'";
$result1=mysql_query($query1);
if(mysql_num_rows($result1)<5)
{
while ($row = mysql_fetch_array($result1))
{
echo ($row[0]);
echo "
";
$sql2 = "SELECT * FROM Users WHERE RefID=$row[0]";
$sql2result = mysql_query($sql2);
$sql2querynum = mysql_numrows($sql2result);
}
}
$query1="SELECT UserID FROM Users where RefID='$userid'";
$result1=mysql_query($query1);
while ($row = mysql_fetch_array($result1, MYSQL_NUM) && $sql2querynum < '5')
{
echo ($row[0]);
echo "
";
$sql2 = "SELECT * FROM Users WHERE RefID={$row[0]}";
$sql2result = mysql_query($sql2);
$sql2querynum = mysql_numrows($sql2result);
}
Use { } for variables in " " ... and why you are not using joins ?

PHP MySQL single column/row display?

I'm trying to get a single result from my database, just one name.
I tried using;
$row = mysql_fetch_array(mysql_query("SELECT * FROM persons WHERE id = '$id'"));
echo $row['name'];
But that din't work, any other way to simply show only one result?
Thanks in advance!
[EDIT:]
(I'm using PHP 5.3)
<?php
include("connection.php");
$id = $_GET['deletid'];
$result = mysql_query("SELECT * FROM persons WHERE id = '$id' LIMIT 1");
if(!$result){
echo mysql_error();
}
if ($row = mysql_fetch_array($result)){
echo $row['name'];
}
echo "<p>id:$id</p>";
?>
If you need just the name and you need just one result you should rewrite your query as follow:
$row = mysql_fetch_array(mysql_query("SELECT name FROM persons WHERE id = '". (int) $id ."' LIMIT 1"));
Now to get the result you should just get it with a
$row['name'];
EDIT
Now that you posted your entire code i got what's wrong: You are deleting that result before getting its name. Basically you delete that user and then you attempt to get its name.
EDIT
<?php
include("connection.php");
if (empty($_GET['deleteid'])) {
exit('"deleteid" is empty');
}
$id = mysql_real_escape_string($_GET['deletid']);
$result = mysql_query("SELECT name FROM persons WHERE id = '". (int) $id ."' LIMIT 1");
if(!$result){
echo mysql_error();
}
$row = mysql_fetch_assoc($result); // for just one result you don't need of any loop
echo $row['name'];
echo "<p>id:". htmlspecialchars($id) ."</p>";
?>
try
$row = mysql_fetch_array(mysql_query("SELECT name FROM persons WHERE id = ". (int) $id));
echo $row['name'];

loop problem within a statement

i hope someone can help about to scream!
basically I am trying to do a few things with the statement below;
First i want to check if the user id exists in member_categories_position.
If it Does i want then to exclude all entries from the second statement where member_id equals all results from the first statement
the third statement is the else statement that displays if the member_id is not present in the member_categories position.
PROBLEM - the result from the first system loops fine, however when i try and insert into the second statement (!='$memid') is produces no results and has no effect. I think the problem is that $memid is a looped result.
How do i get the second statement to say that any member_id that is in member_categories_position will not show in that statement?
$sql2 = "
SELECT *
FROM member_categories_position a
JOIN member_users b
ON b.id = a.member_id";
$rs2 = mysql_query($sql2);
while ($row = mysql_fetch_array($rs2))
{
$memid = "".$row['member_id']."";
}
if(mysql_num_rows($rs2) != 0)
{
$new= "
SELECT *
FROM member_categories
JOIN member_users
ON member_categories.member_id=member_users.id
JOIN member_config
ON member_categories.member_id=member_config.member_id
WHERE
member_categories.categories='$category'
AND member_categories.member_id !='$field'
GROUP BY member_config.member_id
ORDER BY RAND() limit 0,42";
$rs = mysql_query($new);
while ($row = mysql_fetch_assoc($rs))
{
echo "result excluding member ids from the first statement";
}
echo "<div class=\"clear\"></div>";
}
else
{
$new= "
SELECT *
FROM member_categories
JOIN member_users
ON member_categories.member_id=member_users.id
JOIN member_config
ON member_categories.member_id=member_config.member_id
WHERE
member_categories.categories='$category'
GROUP BY member_config.member_id
ORDER BY RAND() limit 0,42";
$rs = mysql_query($new);
while ($row = mysql_fetch_assoc($rs))
{
echo "Result with all member ids";
}
echo "<div class=\"clear\"></div>";
} } <-- (second is a stray from original post)
$memid is not in scope since it appears to be defined inside the loop. Try defining $memid = ''; at the top of your script.. like this.
$memid = '';
$sql2 = "
SELECT *
That way it will be defined when you use it below..

Categories