doufei2355 2008-11-09 15:52
浏览 60
已采纳

如何使用PHP中的对象从MYSQL数据库连接/检索数据?

Generally I connect and retrieve data using the standard way (error checking removed for simplicity):

$db = mysql_select_db("dbname", mysql_connect("host","username","passord"));
$items = mysql_query("SELECT * FROM $db");

while($item = mysql_fetch_array($items)) {
    my_function($item[rowname]);
}

Where my_function does some useful things witht that particular row.

What is the equivalent code using objects?

  • 写回答

2条回答 默认 最新

  • drbmhd9583 2008-11-09 16:18
    关注

    Since version 5.1, PHP is shipped with the PDO driver, which gives a class for prepared statements.

    $dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password); //connect to the database
    //each :keyword represents a parameter or value to be bound later
    $query= $dbh->prepare('SELECT * FROM users WHERE id = :id AND password = :pass');
    
    # Variables are set here.
    $query->bindParam(':id', $id); // this is a pass by reference 
    $query->bindValue(':pass', $pass); // this is a pass by value
    
    $query->execute(); // query is run
    
    // to get all the data at once
    $res = $query->fetchall();
    print_r($res);
    

    see PDO driver at php.net

    Note that this way (with prepared statements) will automatically escape all that needs to be and is one of the safest ways to execute mysql queries, as long as you use binbParam or bindValue.

    There is also the mysqli extension to do a similar task, but I personally find PDO to be cleaner.

    What going this whole way around and using all these steps gives you is possibly a better solution than anything else when it comes to PHP.

    You can then use $query->fetchobject to retrieve your data as an object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!