C9 - 如何获取查询结果以及如何从查询中获取行数?

时间:2015-10-28 21:46:04

标签: php mysql cloud9-ide

我编写了这个获取用户名的函数,需要检查用户是否已经在数据库中。

这是我的代码:

 $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";

当我在终端中运行此查询时,我得到1行结果,但在consol中我得到:“结果集有0行。”

有什么问题?

3 个答案:

答案 0 :(得分:0)

您应该使用 mysqli _ 而不是 mysql _ ,因为不推荐使用mysql_。

首先我看到一个问题:(你正在混合mysql_和mysqli _

您的连接是mysql:

mysql_select_db("myDB",$conn);

更改为:

   $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();
  }

您还应该使用准备好的声明:

$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(); 

当然是你的if语句:

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

答案 1 :(得分:0)

我认为您需要更改连接代码。请看看并尝试这种方式

<?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";

答案 2 :(得分:0)

你试过$rowc = $myData->num_rows;

吗?