-2

I'm trying to make a login/register system and I keep getting the errors: Warning: mysql_query() expects parameter 2 to be resource, integer given in /home/roscapex/public_html/core/functions/users.php on line 8

Warning: mysql_result() expects at least 2 parameters, 1 given in /home/roscapex/public_html/core/functions/users.php on line 8

My code is:

<?php
function user_exists($username) {

$username = sanitize($username);

$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");

return (mysql_result(mysql_query($query, 0) == 1) ? true : false);

}
?>

NOTE This might be a duplicate but I tried all the other relevant questions.

Robby Pool
  • 3
  • 1
  • 4
  • 2
    Please review any of the questions in the "Related" section of the right-sidebar. The answer is pretty much always the same. Do not nest `mysql_query()` inside a fetch or `mysql_result()` call. You must check for success or error. – Michael Berkowski Feb 19 '13 at 22:33
  • basically means you can't fetch the query as it's not returning any rows. Do a check before trying to fetch it by using `mysql_num_rows` However - I recommend looking into PDO, mysql_* is deprecated. – David Feb 19 '13 at 22:33
  • I know its a duplicate I've tried all of the others and none of them worked for me – Robby Pool Feb 19 '13 at 22:35
  • 1
    What does `mysql_error` say? – Explosion Pills Feb 19 '13 at 22:50

1 Answers1

0

There are multiple mistakes in your code. Let me annotate it:

<?php
function user_exists($username) {

$username = sanitize($username);

$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"); // $query now contains the result of the query (a Resource)

// Here you try to run the resource *again* trough mysql_query, with with 2 parameters (which results in the warning). I am not quite sure what you intended.
return (mysql_result(mysql_query($query, 0) == 1) ? true : false);

}
?>

I fixed it.

<?php
function user_exists($username) {
  $username = sanitize($username);  // This hopefully santizes the username. Better use mysql_real_escape_string($username)

  $query = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'";

  $result = mysql_query($query) or die(mysql_error());  // Check if query was successful
  $row = mysql_fetch_array($result); // fetch the first row
  return ($row[0] > 1);  // If there is one or more users with this name, return true.

}
// omit the closing ?>, because it causes trouble, when there are any chars behind it (headers alreay sent error etc.)
iblue
  • 27,950
  • 18
  • 84
  • 126