Several while statements for mysql_fetch_array causing unexpected errors - php

I am having a problem with the while function for a mysql_fetch_array. I have experimented on what to use after the statement and what I have now works better than it did before. I thought i could just run a load of loops inside each other but clearly not. I currently have curly brackets on the first two statements and none on the others, you can see this clearly in the code.
However, what i have now means that having more than one variable after each statement causes the second one to stop working when echoed etc. I am trying to avoid using arrays as variables would be a lot easier to lay out afterwards. Not sure what's going on here. I normally use curly brackets after every statement but that just made the whole thing redundant. What should I do to keep all the variables working? I am not great with PHP yet and thanks for all the help so far!
I am just having a mess around for future purposes so I know i should be using mysqli. I have only recently learnt mysqli so I was just using mysql because i feel more comfortable with it for the time being.
Here is the code anyway:
//fetch favourited artist(s)
$fetchartistFavourite = mysql_query("SELECT * FROM artistfavourites WHERE username = '$username' AND password = '$pass';")or die(mysql_error());
while ($artistFavourite = mysql_fetch_array($fetchartistFavourite)){
$favouritedArtist = $artistFavourite['artistname'];
$favouritedArtistUrl = $artistFavourite['artisturl'];
//fetch favourite track(s)
$fetchtrackFavourite = mysql_query ("SELECT * FROM trackfavourites WHERE username = '$username' AND password = '$pass'")or die(mysql_error());
while ($trackFavourite = mysql_fetch_array($fetchtrackFavourite)){
$favouritedTrack = $trackFavourite['artistname'];
$favouritedTrackUrl = $trackFavourite['artisturl'];
//Get news from favourited artist(s)
//Get updates to bio
$fetchupdatedBio = mysql_query ("SELECT * FROM members WHERE artistname = '$favouritedArtist'")or die(mysql_error());
while ($updatedBio = mysql_fetch_array($fetchupdatedBio))
$updatedBio = $updatedBio['bio'];
//Get updates to profile pic
$fetchupdatedProfile = mysql_query ("SELECT * FROM members WHERE artistname = '$favouritedArtist'")or die(mysql_error());
while ($updatedProfile = mysql_fetch_array($fetchupdatedProfile))
$updatedProfile = $updatedProfile ['image1'];
//Get any new pictures
$fetchPic = mysql_query ("SELECT * FROM pictures WHERE artistname = '$favouritedArtist'")or die(mysql_error());
while ($pic = mysql_fetch_array($fetchPic))
$pic = $pic['picurl'];
//Get any new tracks
$fetchTracks = mysql_query ("SELECT * FROM tracks WHERE artistname = '$favouritedArtist'")or die(mysql_error());
while ($tracks = mysql_fetch_array($fetchTracks))
$trackurl = $tracks['trackurl'];
$trackname = $tracks['trackname'];
//Get any new gigs
$fetchGigs = mysql_query ("SELECT * FROM gigs WHERE artistname = '$favouritedArtist'")or die(mysql_error());
while ($gigs = mysql_fetch_array($fetchGigs))
//arrange gig data into format to be echoed
$gig = $favouritedArtist.' is playing for the gig ' .$gigs['gigname'].' at ' .$gigs['venue'].' on the '.$gigs['day'].'th of '.$gigs['month'].', '.$gigs['year'];
//Get any new sessions
$fetchSessions = mysql_query ("SELECT * FROM sessions WHERE artistname = '$favouritedArtist'")or die(mysql_error());
while ($sessions = mysql_fetch_array($fetchSessions))
$sessionName = $sessions ['title'];
//Get new tracks from favourited tracks(s)if the artist has not been favourited
$fetchnewTrack = mysql_query ("SELECT * FROM tracks WHERE artistname = '$favouritedTrack' AND artistname !='$favouritedArtist'")or die(mysql_error());
while ($newTrack = mysql_fetch_array($fetchnewTrack))
$trackname2 = $newTrack['trackname'];
//asign all variables into an
echo $trackname;
}
}

First of all, you should definitely try not to SELECT *, but just the content you need.
Like :
SELECT picurl FROM pictures WHERE artistname = '$favouritedArtist'
instead of
SELECT * FROM pictures WHERE artistname = '$favouritedArtist'
In your :
while ($tracks = mysql_fetch_array($fetchTracks))
$trackurl = $tracks['trackurl'];
$trackname = $tracks['trackname'];
There is an error, because you don't need brackets only when there is a single instruction after the while statement.
Idem with your
while ($sessions = mysql_fetch_array($fetchSessions))
with no brackets, you can't do so if there is more than one instruction related to the while.
While are only needed when you know there will be multiple answers in you MySQL request. Since the might be only one user with this username, you don't need a while.
All of this are basics of php and mysql development, a simple google search would have given you the answer.
I think you might need to read some more tutorials on basics of php and mysql.

Related

PHP mysql_fetch_array multiple tables

So I have the below code that I'm trying to run partly as a login script, and partly to gather some information for another program. I don't get any errors with the script, I just don't get any information from the second and third mysql_fetch_array which I read is a common problem but that should only apply to the same table. Even so, I followed the recommended advice and used mysql_data_seek to reset the $result. I've also tried using different $result and $row variables but I still don't get any data back from those queries. Any thoughts on how I can do this?
$result = mysql_query("SELECT * FROM user WHERE username = '$username'");
$row = mysql_fetch_array($result);
$salt = $row['salt'];
$id = $row['id'];
$usergroup = $row['usergroupid'];
$mysql_pass = $row['password'];
$md5_pass = md5($password.$salt);
mysql_data_seek ($result, 0);
if($mysql_pass == $md5_pass)
{
$result = mysql_query("SELECT teamid FROM tmnt_members WHERE teamid = '$id'");
$row = mysql_fetch_array($result);
$team = $row['teamid'];
$captain = $row['leader'];
$cocaptain = $row['coleader'];
mysql_data_seek ($result, 0);
$result = mysql_query("SELECT * FROM tmnt_teams WHERE teamid = '$team'");
$row = mysql_fetch_array($result);
$teamname = $row['teamname'];
}
You're missing your coleader and leader fields in your second query. Your three queries can be written as one quite simply.
SELECT *
FROM user u, tmnt_members m, tmnt_teams t
WHERE u.username = '$username'
AND m.teamid = u.id
AND t.teamid = m.teamid
Or if you would like to keep the authentication a separate query, you could do SELECT * FROM user WHERE username = '$username' followed by:
SELECT *
FROM tmnt_members m, tmnt_teams t
WHERE m.teamid = '$id'
AND t.teamid = m.teamid
While writing this, I noticed there probably is an error in your second query. The condition teamid = '$id' seems pretty strange. Currently, you're fetching the team which has an ID that is the one of the user. That can't be correct, or if it is, your database structure is very, very strange. I guess it should be something like memberid = '$id'.
Also notice that without the corrections suggested in my first paragraph, this query is asking the database to fetch the ID of a team which has the ID $id. In other words, you could've just used $id directly if that query was correct.
Moreover, doing a SELECT * isn't the best practice; it's better to enumerate all the fields you want explicitly. If you change your column names or do some other modifications to your database, your query may still work, but may not do what you expect it to do.
I've converted your code to MySQLi at least. I have quoted my comments inside. And did try to clean your code. Try this:
<?php
$con=mysqli_connect("Host","Username","Password","Database"); /* REPLACE NECESSARY DATA INSIDE */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$username=mysqli_real_escape_string($con,$_POST['username']); /* ASSUMING $username COMES FROM A POST DATA. JUST REPLACE IF NECESSARY */
$result = mysqli_query($con,"SELECT * FROM user WHERE username = '$username'");
while($row = mysqli_fetch_array($result)){
$salt = mysqli_real_escape_string($con,$row['salt']);
$id = mysqli_real_escape_string($con,$row['id']);
$usergroup = mysqli_real_escape_string($con,$row['usergroupid']);
$mysql_pass=mysqli_real_escape_string($con,$row['password']);
$md5_pass = md5($password.$salt); /* MAKE SURE YOU HAVE $password AND $salt VARIABLES DECLARED ABOVE */
if($mysql_pass == $md5_pass)
{
$result2 = mysqli_query($con,"SELECT teamid, leader, coleader FROM tmnt_members WHERE teamid = '$id'"); /* ADDED leader AND coleader */
while($row2 = mysqli_fetch_array($result2)){
$team = mysqli_real_escape_string($con,$row2['teamid']);
$captain = mysqli_real_escape_string($con,$row2['leader']);
$cocaptain = mysqli_real_escape_string($con,$row2['coleader']);
$result3 = mysqli_query($con,"SELECT * FROM tmnt_teams WHERE teamid = '$team'");
while($row3 = mysqli_fetch_array($result3)){
$teamname = mysqli_real_escape_string($con,$row3['teamname']);
} /* END OF THIRD LOOP */
} /* END OF SECOND WHILE LOOP */
} /* END OF IF MYSQL_PASS IS EQUALS TO MD5_PASS */
/* IS THIS WHERE YOU WANT TO PRINT YOUR RESULTS? */
echo $id." ".$usergroup." ".$team." ".$captain." ".$cocaptain. " ".$teamname;
} /* END OF WHILE LOOP */
?>

How WHERE clause works when inserting php variables

I am having problems trying to get these queries with a WHERE clause to work. I have two tables which look like this :
What I am trying to do is return the genre that each film has. At the moment no data is returning at all from what I can see. Here are the two queries:
$film_id = $row_movie_list['film_id'];
mysql_select_db($database_fot , $fot);
$query_get_genre = "SELECT * FROM film_genre WHERE `id_film` ='". $film_id. "'";
$get_genre = mysql_query($query_get_genre, $fot) or die(mysql_error());
$row_get_genre = mysql_fetch_assoc($get_genre);
$totalRows_get_genre = mysql_num_rows($get_genre);
$genre_id = $row_get_genre['id_genre'];
mysql_select_db($database_fot , $fot);
$query_genre = "SELECT * FROM genre WHERE `id_genre` ='". $genre_id. "'";
$genre= mysql_query($query_genre, $fot) or die(mysql_error());
$row__genre = mysql_fetch_assoc($genre);
$totalRows_genre = mysql_num_rows($genre);
PHP with content area. I fairly new to PHP so any help would be appreciated.
<?php do { echo $genre['genre']; } while($row_get_genre = mysql_fetch_assoc($get_genre)); ?>
Update: I am now able to get first genre but not second it just echos the first one twice and I have tried but still no luck:
do {do { echo $row_genre['genre']; } while($row_genre = mysql_fetch_assoc($genre));} while($row_get_genre = mysql_fetch_assoc($get_genre)); ?>
Avoiding the fact that you're using a deprecated way to establish connection and interact with MySQL, what you're doing is getting a single relation genre-film and then getting the row of the genre that matches. You should surround part of your code with a while that executes while it's still genres of the film with id. Something like:
$film_id = $row_movie_list['film_id'];
mysql_select_db($database_fot , $fot);
$query_get_genre = "SELECT * FROM film_genre WHERE `id_film` ='". $film_id. "'";
$get_genre = mysql_query($query_get_genre, $fot) or die(mysql_error());
while($row_get_genre = mysql_fetch_assoc($get_genre)){
$genre_id = $row_get_genre['id_genre'];
$query_genre = "SELECT * FROM genre WHERE `id_genre` ='". $genre_id. "'";
$genre= mysql_query($query_genre, $fot) or die(mysql_error());
$row__genre = mysql_fetch_assoc($genre);
// You should do whatever you want to do with $row__genre here. Otherwise it will be cleared.
}
I must insist this is a deprecated and insecure way of communication with a MySQL Database. I recommend you read about MySQLi or PDO extensions.
MySQLi: http://www.php.net/manual/en/book.mysqli.php
PDO: http://www.php.net/manual/en/book.pdo.php

how to get a particular field from a database via php

I am trying to get four different values from my database. The session variable username and usernameto are working, but I want to get 4 different values -- two each from username and usernameto:
<?php
session_start(); // startsession
$Username=$_SESSION['UserID'];
$Usernameto= $_SESSION['UserTO'];
$db = mysql_connect("at-web2.xxxxxx", "yyyyy", "xxxxxxx");
mysql_select_db("db_xxxxxx",$db);
$result1 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
while($myrow1)
{
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
while($myrow2)
{
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
?>
Edit - just realized that you didn't tell us what wasn't working about the code you provided. Are you getting an error message or are you not getting the correct data back? You still should fix your query, but we'll need some more information to know what's wrong.
Your query statements shouldn't have "and" between the select parameters, so it should be:
Edit 2 - I just noticed that you had a while loop that you don't need, try this:
$result1 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
if (isset($myrow1)) {
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
if (isset($myrow2)) {
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
An example from the php manual echoing an html table
I don't know if you can derive what you need from this?
More specific: You can use:
$line = mysql_fetch_array($result, MYSQL_ASSOC);

PHP nesting quotes

The following fails:
$result = mysql_query("SELECT * FROM Tasks WHERE UserID = '$_SESSION['userID']'");
I tried the following:
$userID = $_SESSION['userID'];
$result = mysql_query("SELECT * FROM Tasks WHERE UserID = '$userID'");
and it works. Is there a way to do this without making a separate variable?
Thanks!
Or like this:
$result = mysql_query("SELECT * FROM Tasks WHERE UserID = '{$_SESSION['userID']}'");
$result = mysql_query("SELECT * FROM Tasks WHERE UserID = '".$_SESSION['userID']."'");
or
$result = mysql_query("SELECT * FROM Tasks WHERE UserID = '{$_SESSION['userID']}'");
worth noting it would recommend the first one because it gets easier to read/find when you use a php editor, which in return makes it easier to debugg
Your first chokes the query, because you're actually commanding WHERE userID is '$_SESSION['. Not to mentions that rest which is userID']}' will be interpreted as a syntax error by MySQL.
Yes, like this
$result = mysql_query("SELECT * FROM Tasks WHERE UserID = '$_SESSION[userID]'");

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

Categories