-8

Is my code being inputted correctly. I am trying to SELECT from my database a set of numbers. Here is the code:

mysql_connect(db_server, db_user, db_pass);
$result = mysql_db_query(db_name,"SELECT *, COUNT(track.usr_id) AS usr_views FROM user, track WHERE track.usr_id = $usr_id AND track.timesin = $les_tag GROUP BY $usr_id ORDER BY usr_views LIMIT 1");      
$usercheck = mysql_result($res, 0, 0); 
$Userstats = $usercheck;  

Am I selecting the code wrong?

  • 3
    How should we know? We have no idea what your database structure is, or what your variables contain. – Quentin Dec 15 '13 at 21:14
  • If they were suppose to be numbers like 5 or 10? – user3102920 Dec 15 '13 at 21:14
  • `mysql_result()` returns a resource, not data. You need to retrieve the data with `mysql_fetch_array()` or similar. –  Dec 15 '13 at 21:15
  • Your code has at least two errors in it. What is db_name? What is $res? – Andrew Schulman Dec 15 '13 at 21:16
  • `mysql` is deprecated, either use [mysqli](http://us1.php.net/mysqli) or [PDO](http://us3.php.net/PDO). Also your code is vulnerable to [SQL injections](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1). –  Dec 15 '13 at 21:17
  • 1
    Why are you directly including variables into your query? You should be using prepared statements unless you like being vulnerable to SQL injection attacks. – Venge Dec 15 '13 at 21:17
  • @André — It may or may not be vulnerable to SQL injections (we can't tell because we can't see how the variables are set), but the `mysql_` library certainly shouldn't be used today. – Quentin Dec 15 '13 at 21:18

1 Answers1

0

Try this...

$conn = mysql_connect(db_server, db_user, db_pass);
if ($conn !== false) {
    mysql_select_db(db_name);
    $result = mysql_query("SELECT *, COUNT(track.usr_id) AS usr_views FROM user, track WHERE track.usr_id =     $usr_id AND track.timesin = $les_tag GROUP BY $usr_id ORDER BY usr_views LIMIT 1");      
    if ($result !== false && mysql_num_rows($result) > 0) {
        $usercheck = mysql_fetch_row($result); 
        $Userstats = $usercheck;
    }
} else {
     die("There was an error while connecting to the mysql server");
}
mattmc
  • 479
  • 5
  • 14