1

I wrote this function that get user name and need to check if the user is already in the DB.

This is my code:

 $conn = new mysqli($servername, $username, $password, $database, $dbport);
 mysql_select_db("myDB",$conn);
 //$sql="CALL checkIfExsist(".$name.")";
 $sql = "select * from Users where userName='".$name."' LIMIT 1;";
 $myData = $conn-> query($sql);
 $rowc = mysqli_num_rows($myData);
 printf("Result set has %d rows.\n", $rowc);
  if($rowc > 0)
  {
      echo "User ".$name." checked";

  }
  else
     echo "not exsist";

When I run this query in the terminal i get 1 row result, but in the consol I get: "Result set has 0 rows."

What is the problem?

galkogi
  • 33
  • 4

3 Answers3

0

You should use mysqli_ instead of mysql_ as mysql_ is deprecated.

firstly I see a problem: ( you are mixing mysql_ and mysqli_ )

Your connection is mysql:

mysql_select_db("myDB",$conn);

Change to:

   $conn=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

You should also use prepared statements:

$stmt = $mysqli->prepare('SELECT * FROM Users WHERE userName = ?')
$stmt->bind_param('s', $username);
 if(!$stmt->execute()){
trigger_error("there was an error....".$mysqli->error, E_USER_WARNING);
} 
$stmt->store_result(); 

Then of course your if statement:

     if ($stmt->num_rows > 0){
         echo "User ".$name." checked";
    }else
         echo"User doesn't exist"
0

I think you need to change your connection code. please have a look and try by this way

<?php

define("DB_HOST", "db_host");
define("DB_USER", "db_user");
define("DB_PASSWORD", "db_pass");
define("DB_DATABASE", "db_name");
$conn= mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,DB_DATABASE );

 $sql = "select * from Users where userName='".$name."' LIMIT 1;";
 $myData = $conn->query($sql);
 $rowc = mysqli_num_rows($myData);
 printf("Result set has %d rows.\n", $rowc);
  if($rowc > 0)
  {
      echo "User ".$name." checked";

  }
  else
     echo "not exsist";
Shaymol Bapary
  • 468
  • 3
  • 11
0

did you try $rowc = $myData->num_rows;

Karan
  • 2,102
  • 2
  • 22
  • 31
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – IKavanagh Oct 29 '15 at 07:29
  • @IKavanagh Thanks for suggestion, but i was not able to post comment at that time(due to less reputation). – Karan Oct 29 '15 at 07:57