使用php和MYSQLI从数据库读取单个记录的简单方法

时间:2015-11-19 00:08:02

标签: php mysql mysqli

如何使用php和mysqli将PHP更改为从数据库中读取单个记录? 这就是我目前所拥有的:

$description = mysql_result(mysql_query("SELECT description FROM usermeta WHERE meta_key = 'description' AND user_id = 1 LIMIT 1"),0);  

我应该如何更改它以使用mysqli

2 个答案:

答案 0 :(得分:1)

  

以下是一个简单的mysqli解决方案:

$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
  

如果您抓住多行,我会这样做:

$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
    echo "{$row['field']}";
}
$resource->free();
$db->close();
  

使用错误处理:如果发生致命错误,脚本将以错误消息终止。

// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
    echo "{$row['field']}";
}
$resource->free();
$db->close();
  

获取单个记录:此代码不需要循环。

$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
  

使用迭代器:PHP 5.4添加了支持

$db = new mysqli('localhost','user','password','database');
foreach ( $db->query('SELECT * FROM table') as $row ) {
    print_r($row);//echo "{$row['field']}";
}
$db->close();

答案 1 :(得分:0)

不要使用已弃用的mysql_*函数。您可以使用这样的PDO / Prepared语句:

define('DB_HOST', 'localhost');
define('DB_NAME', 'your_database');
define('DB_USER', 'your_username');
define('DB_PASSWORD', 'your_passworde');

try {
    //Make your connection handler to your database
    $conn = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));

    $user_id = 1;   //Your user input variable here

    $sql = "SELECT description FROM usermeta WHERE meta_key = 'description' AND user_id = :user_id LIMIT 1";
    //Prepared statements so no SQL Injection occurs
    $stmt = $conn->prepare($sql);
    //Execute your query
    $stmt->execute(array(':user_id'=>$user_id));

} catch(PDOException $e) {
    echo $e->getMessage();
    die();
}

另请查看mysqli prepared statements