Please help me to debug this code - php

Bit confused with this one.
Basically, I have a column in a table, and I want to retrieve the value in that column, for a specific row.
I have one set of code that works, but not in this particular situation.
The code I have that works is this:
$qry="SELECT * FROM logins WHERE username='$login' AND password='$password'";
$result=mysql_query($qry);
This obviously retrieves that particular row, and then:
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['User ID'];
This successfully sets the session variable, as the value from the user id column from this row.
So that's fine, that works. The code I am trying to use in my new situation is this:
$qry = "SELECT * FROM vote WHERE Username = '" .$_SESSION['SESS_USERNAME']. "'";
$result = mysql_query($qry);
This gets the row based on the current user, and then:
while($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}
The while loop works correctly, it displays the current username, and their vote. Obviously I felt the loop was not required as I already have just the one row selected. Removing the loop broke it, so I put it back. Not a big deal, I can live with that if it gets the job done.
The issue I am focusing on, is the use of the
$row['Username']
In this if statement:
if($row['Username'] == "Admin") {
echo ("Win!<br />");
}
else {
echo "Failed!";
}
When printing from the loop above, it prints:
Name, as Admin,
and vote, as 0.
If I then try to validate using the if statement, I ask it to echo Win! if the username == Admin.
Obviously it is true as it has printed it on the line before, however, it always prins Fail! and I can't understand why.
Should I set $row['Username'] as some other variable?
Can anyone offer their guidance please?
Cheers
Eds

The problem stems from your loop:
while($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}
The first time through, $row is set to the row of data from the database. It then tries to go through the loop again, but since there is only one row, mysql_fetch_array returns false. now $row is set to false. So any code after the loop won't have access to the data anymore.
The solution would be to replace your loop with a simple if statement:
if ($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}

I fail to see how your PHP code could produce that "it prints" sample. However, check that your Username field actually contains an exact "Admin" string. It may have a linebreak or other whitespace in it. Doing a
var_dump($row['Username']);
should show something like
string(5) Admin
The bracketed number (5) is the length of the string. If it's not 5, then you've got some extra stuff in the string causing the == 'Admin' test to fail.

Related

How to insert information from database into my php/display on my website?

All my information is going into the database that is being saved but I want it to come back up when I log in using a unique email. I have tried a lot of different codes within php. This is what I recently tried.
$result_habit = mysqli_query ($con, $query_habit);
if (mysqli_num_rows($result_habit) ==1) {
echo "found the row for ", $Email;
$row = mysqli_fetch_row($result_habit);
echo "$row[c1]"
I want it to display the information from the table 'habit' and each row is labeled c1, c2, c3, etc
Is there anything else I have to do to get the saved data to display for each unique login email?
thanks
$result_habit = mysqli_query ($con, $query_habit);
if (mysqli_num_rows($result_habit) == 1) {
echo "found the row for ", $Email;
$row = mysqli_fetch_row($result_habit);
echo $row['c1'];
}
This should be the correct way to write the code. All you seemed to have missed was a closing bracket and echoing the row variable correctly.

Nested while loop in PHP is not working for MySQL database queries

All the whole day I'm trying to solve this problem but still no luck.
The scenario is: I am developing a vertical menu which should query groups and items of those groups in a menu respectively, but groups are being populated without its items.
Code was written in the following way:
$data1 = mysql_query(select groupnames from groups where categoryy='Agriculture');
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$data2==mysql_query(select itms from groupitems where categoryy='Agriculture' and groupname='$info1[0]');
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
In the above code, groups are being populated nicely but no items from groupitems table are being populated. If I write Grain (Grain is one of the group of agriculture in my database) instead of groupname=$info1[0] then it works. But it should be got dynamically from the query.
Please help, I'm in trouble.
at last its solved! here's the code:
<?php
include "aPannel/dbconn.php";
$query="select GroupName from categorygroup where categoryy='Agriculture'";
$i=0;
$result=mysql_query($query);
$num=mysql_num_rows($result);
$groupname=mysql_result($result ,$i ,"GroupName");
mysql_close();
if ($num=="0") echo "<p>Sorry, there are no groups to display for this Category.</p>";
else
{
echo "<p>There are currently <strong>$num</strong> groups represented in our database.</p><br>";
while($i < $num)
{
$groupname=mysql_result($result ,$i ,"GroupName");
include("aPannel/dbconn.php");
$query2 = "SELECT subcategory FROM groupsubcategory WHERE groupname='$groupname'"; // count number of items in each group
echo $query2 . "<br/>";
$resultt=mysql_query($query2);
$countt=mysql_num_rows($resultt);
mysql_close();
echo $countt . "subcategories" . "<br/>"; // display number of items
$i++;
}
} // end if results
?>
Your queries are not wrapped around double-quotes (" ") . Always remember that what you pass to mysql_query method is a string argument. And also $data2==.... seems wrong.
So, change the code like this
$data1=mysql_query("select groupnames from groups where categoryy='Agriculture'");
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$infoTemp=$info1[0];
$data2=mysql_query("select itms from groupitems where categoryy='Agriculture'
and groupname='$infoTemp'");
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
I hope it should work
EDIT: Also are you sure column itms in second query or items ?
EDIT: added temporary variable

mysql_fetch_array() not spiting anything

Here is my code:
$campagin_id = $_SESSION['campagin_id_for_camp'];
$query = "SELECT * FROM survey_result where campagin_id = ".$campagin_id;
$conn=mysql_connect($dbconfig['db_hostname'],$dbconfig['db_username'],$dbconfig['db_password']) or die(mysql_error());
mysql_select_db($dbconfig['db_name'],$conn);
$exec_query =mysql_query($query) or die(mysql_error());
$row=mysql_fetch_array($exec_query);
echo "<br> row = ".$row;
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
The Problem is that I am not getting anything in $row I cant get into the while loop, nothing shows up when I try to echo the value of $row, No error Nothing. Can you help me to find a problem in my code ?
Ps : The database is their. I have checked for the query for the corresponding value of $campagin_id. and also when i tried to echo $exec_query it echoed this : Resource id #8
PPS : The database have more than 7 record for each id so it doesn't matter if I call mysql_fetch_array($exec_query) more than once before going in to the while loop. and for the $campagin_id in the session their are many records present in the database.
You have written $row=mysql_fetch_array($exec_query) and then you are echoing something. and you are using the same in while.
Instead of:
$row=mysql_fetch_array($exec_query);
echo "<br> row = ".$row;
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
Use this (as per my knowledge you should not use $row=mysql_fetch_array() once you have used before while):
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
If the query returns Resource id #8 then that means it was successful - ie there were no errors. There were probably no rows returned by that query, so no rows in your table that match the given campagin_id.
You are also calling mysql_fetch_array() twice separately, you shouldn't do that because your while loop will skip the first row because calling this moves the pointer in the result set forward by one.
Also you can't echo an array as you are trying to, if you want to see the contents of an array use print_r() or var_dump().
I suggest adding some code to handle no rows found:
if($exec_query && mysql_num_rows($exec_query) > 0)
{
while ($row=mysql_fetch_array($exec_query)){
echo "Row: " . print_r($row, true);
}
}
else
{
echo 'None found';
}
Try this code.
<?
$campagin_id = $_SESSION['campagin_id_for_camp'];
$query = "SELECT * FROM survey_result where campagin_id = ".$campagin_id;
mysql_connect($dbconfig['db_hostname'],$dbconfig['db_username'],$dbconfig['db_password']) or die(mysql_error());
mysql_select_db($dbconfig['db_name']);
$exec_query =mysql_query($query) or die(mysql_error());
while ($row=mysql_fetch_assoc($exec_query)) {
echo "<br/> row = <pre>".print_r($row)."</pre><br/>";
}
?>

Multiple MySQL records with same name, different id

There might be an easy answer to this, but I can't for the life of me get this to work.
I'm using PHP and MySQL and have something like this set up:
$studentname = mysql_real_escape_string($_POST['sname']);
$studentnumber = mysql_real_escape_string($_POST['snumber']);
$course = mysql_real_escape_string($_POST['courseselect']);
$bike3 = mysql_query("SELECT stoodnumber FROM bikes505 WHERE stoodname='" . $studentname . "'");
$bikestoods = mysql_fetch_array($bike3);
while($row = mysql_fetch_array($stoodlistq))
{
$stoodentname = $row['stoodname'];
$stoodentnumber = $row['stoodnumber'];
//$coursename = $row2['coursename'];
//$coursecode = $row2['coursecode'];
if($studentname == $stoodentname && $studentnumber == $stoodentnumber){
//$success = 1;
//$success = "yupp";
//echo "SUCCESS, WE CAN REGISTER YOOOU!";
echo "<br>";
//echo "INSERT INTO " . $course . "";
switch($course){
case "Biking Safely":
if($studentnumber = $bikestoods[0] or $bikestoods[1]){
echo "Sorry, this student has already registered";
} else if($bikecurrent < $bikemax){
mysql_query("INSERT INTO bikes505 VALUES ('" . $stoodentname . "','" . $stoodentnumber . "')");
echo "Yay, successfully registered " . $stoodentname . " - " . $stoodentnumber . " for " . $course;
echo "<br>";
} else{
echo "Sorry, class is full!";
}
break;
...and so on. The only problem that I'm having is that if I have two students with the same name, the second in the list will echo that the information is not correct.
For example, the MySQL table has 'stoodname' and 'stoodnumber', and if 'Jimmy St.James','1010' and 'Jimmy St.James','1090' are both records in the table it will only let me enroll Jimmy 1010 in the course and not Jimmy 1090.
Am I just way off with how I'm validating? Or am I missing something really obvious? At first I assumed it was just because I was only using the first item in the array $bikestoods[0] so I changed it to $bikestoods[0] or $bikestoods[1] and it still doesn't work.
Per a comment, you have $stoodlistq defined as:
$stoodlistq = mysql_query("SELECT * FROM stoodinfo");
Later, you use the following block of code:
$studentname = mysql_real_escape_string($_POST['sname']);
$studentnumber = mysql_real_escape_string($_POST['snumber']);
...
while($row = mysql_fetch_array($stoodlistq)) {
...
if($studentname == $stoodentname && $studentnumber == $stoodentnumber){
The while() loop in this code iterates over every record, however, the if-statement checks against the POST variables. The POST variables make up a single combination for "one student" - therefore, you'll only ever get a single student that can be enrolled.
To fix the issue, you'll either need to update your form that submits the "student name"/"student number" to accept multiple inputs - or update the if-statement to only check against the student's name (which could lead to a more undesired situation).
You are doing your query looking for stoodname . When you are doing things like this is not good to do this statements by a value that can be repeated. Maybe you want them to login with a username and password, or maybe with an id that you give to them, but unless somebody here has a better idea, i don't think you will be able to do it by the name.
$bikestoods = mysql_fetch_array($bike3);
only refers to the first result of bike3 query and only has 2 cols : [0] and [stoodnumber] no [1]. If you want to collect all ids that are in bike3, you have to curse the result one time.
while($stoodnumbers[] = mysql_fetch_array($bike3));

Displaying results after MySQL JOIN query with PHP

$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
echo $rows[0][1].$rows[0][0];
/* for($i=0;$i<=10;$i++)
{
echo $rows[i][1].$rows[i][0];
}
*/
This script is supposed to show the last 10 messages in a chat.What I'm doing is getting the Name of the user from the users table and the text from the message table and I want to display them in my chat window.Right now I have only 4 messages recorded and don't know how this affects the whole script I should implement a check for this too, but the bigger problem is that when i use echo $rows[0][1].$rows[0][0]; the info is displayed correctly, but when I try to make a loop so I can show tha last 10 (I tried the commented one) then nothing is displayed.I thought at least when I use this loop I'll see the 4 recorded messages but what really happen is a blank window.Obvously I have the info recorded in $rows[] and can echo it, but don't understand why this loop don't work at all.I'll appreciate if someone can help me with this and with the check if the messages are less then 10.
Thanks.
Leron
P.S
Here is the edited script, thanks to all of you, I need the array because otherwise the most recent message is shown at the top which is not an opiton when I use it for diplaying chat masseges.
for($i=10;$i>=0;$i--)
{
if($rows[$i][1]!="" || $rows[$i][0]!="")
{
echo $rows[$i][1].' : '.$rows[$i][0];
echo "</br>";
}
}
Your FOR loop was running 11 times even if only 10 records. The second clause should be a < instead of <=. Plus the $ was missing on the i variable.
For example sake, you don't really need to make an array from the rows, and you can refer to the fields by name:
while($row = mysql_fetch_array($result))
{
echo $row['name'] . ' says: ' . $row['message'] . '<BR>';
}
why not just do
while($row = mysql_fetch_array($result))
{
echo $row[1]." ".$row[0];
}
Your query, auto limits it to the last 10, this will then show anything from 0 to 10 which get returned.
PS I added a space between username and message for readability
You need $ symbols on your i variable:
for($i=0;$i<10;$i++)
{
echo $rows[$i][1].$rows[$i][0];
}
A more robust solution would be like this:
$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row[1].$row[0];
}

Categories