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 */
?>
Related
Basically, I have been having some trouble with sending a request to a MySQL server and receiving the data back and checking if a user is an Admin or just a User.
Admin = 1
User = 0
<?php
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`";
$checkAdmin = $checkAdminQuery
mysqli_query = $checkAdmin;
if ($checkAdmin == 1) {
echo '<h1>Working!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
Sorry that this may not be as much info needed, I am currently new to Stack Overflow.
Firstly, your SQL query is wrong
SELECT * FROM `users` WHERE `admin`
It's missing the rest of the WHERE clause
SELECT * FROM `users` WHERE `admin` = 1
Then you're going to need fetch the result from the query results. You're not even running the query
$resultSet = mysqli_query($checkAdminQuery)
Then from there, you'll want to extract the value.
while($row = mysqli_fetch_assoc($resultSet))
{
//do stuff
}
These are the initial problems I see, I'll continue to analyze and find more if needed.
See the documentation here
http://php.net/manual/en/book.mysqli.php
You need to have something like user id if you want to check someone in database. For example if you have user id stored in session
<?php
// 1. start session
session_start();
// 2. connect to db
$link = mysqli_connect('host', 'user', 'pass', 'database');
// 3. get user
$checkAdminQuery = mysqli_query($link, "SELECT * FROM `users` WHERE `id_user` = " . $_SESSION['id_user'] );
// 4. fetch from result
$result = mysqli_fetch_assoc($checkAdminQuery);
// 5. if column in database is called admin test it like this
if ($result['admin'] == 1) {
echo '<h1>Is admin!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
// get all admin users (assumes database already connected)
$rtn = array();
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`=1";
$result = mysqli_query($dbcon,$checkAdminQuery) or die(mysqli_error($dbconn));
while($row = mysqli_fetch_array($result)){
$rtn[] = $row;
}
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`"; !!!!
where what ? you need to specify where job = 'admin' or where name ='admin'
you need to specify the column name where you are adding the admin string
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);
I have the following code that fetches a single row:
$query = "SELECT *
FROM translations
WHERE iddoc = '$id'
AND submitted = 1;";
$result = mysqli_query($query);
$row = mysqli_fetch_array($result);
I know this is useful in a while loop, where you can just loop through the results.
But I need to be able to grab specific rows that meet this condition. Something following this pseudo code:
$query = "SELECT *
FROM translations
WHERE iddoc = '$id'
AND submitted = 1;";
$result = mysqli_query($query);
$arrayofrows = mysqli_fetch_arrayofrows($result);
$arrayofrows[0] //(to get the first row)
$arrayofrows[1] //(2nd row)
and so on...
How can I do this?
You can try something like this
$arrayofrows = array();
while($row = mysqli_fetch_array($result))
{
$arrayofrows = $row;
}
You can now have
$arrayofrows[0] //(to get the first row)
$arrayofrows[1] //(2nd row)
I think the function you are looking for is mysqli_fetch_all as shown below. This avoids the need to create an extra looping structure or a function to do something already provided.
$query = "SELECT *
FROM translations
WHERE iddoc = '$id'
AND submitted = 1;";
$result = mysqli_query($query);
$arrayofrows = mysqli_fetch_all($result);
$arrayofrows[0] //(to get the first row)
$arrayofrows[1] //(2nd row)
It depends on whether you require the entire result set back or not but I think the LIMIT could be used like:
$query = "SELECT *
FROM translations
WHERE iddoc = '$id'
AND submitted = 1 LIMIT 200,200;";
Otherwise as others say you will need to convert to an array (which is what fetch_all does) and then get the element from that array.
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.
So I'm trying to fetch data in a many-to-many relationship.
So far I have this, which finds the user:
$user = $_SESSION['user'];
$userID = mysql_query("SELECT * FROM users WHERE user='$user'") or die(mysql_error());
And I know that to echo this information I have to put it in an array like so:
while ($r = mysql_fetch_array($userID)) {
echo $r["0"];
}
This works fine, but when I try to find this variable in another table, I'm not sure what to use as the variable:
$projects = mysql_query("SELECT projects_ID FROM projects_users WHERE users_ID='???'") or die(mysql_error());
I've tried replacing ??? with $userID and $r, but to no avail. I know the code works because it's fine when I put a user ID in manually - where have I gone wrong?
$user = $_SESSION['user'];
$query = mysql_query("SELECT * FROM users WHERE user='".mysql_real_escape_string($user)."' LIMIT 1") or die(mysql_error()); //--note the LIMIT
$result = mysql_fetch_array($query);
$userID = $result[0];
$projects = mysql_query("SELECT projects_ID FROM projects_users WHERE users_ID='$userID'") or die(mysql_error());
Untested, but this should work:
$user = mysql_real_escape_string($_SESSION['user']);
$query = mysql_query("SELECT * FROM users WHERE user='$user'") or die(mysql_error());
$result = mysql_fetch_array($query);
$userID = $result[0];
$projects = mysql_query("SELECT projects_ID FROM projects_users
WHERE users_ID='$userID'") or die(mysql_error());
I your case, you'd need to place $r[0] there.
I think this code is helpful for beginners when you want to get data in array form
we use mysqli instead of mysql to protecting your data from SQL injection.
Before use this code check the database connection first
<?php $tableName='abc';
$qry="select * from $tableName";
$results=mysqli_query($qry);
while($records=mysqli_fetch_array($results))
{
$firstrecord=$records[1];
$secondrecord=$records[2];
}
?>
You can get your projects with one query:
$user = mysql_real_escape_string($_SESSION['user']);
$query = mysql_query("SELECT pu.projects_ID FROM users u
INNER JOIN projects_users pu ON (pu.users_ID = u.users_id)
WHERE u.user='$user'") or die(mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['projects_ID'];
}