【问题标题】:Convert PHP file To PDO [closed]将 PHP 文件转换为 PDO [关闭]
【发布时间】:2014-09-18 22:45:12
【问题描述】:

我是 php 的初学者,我需要你的帮助。我想为 PDO 制作以下代码,以便为我正在尝试构建的 android 应用程序提供 json 输出。我尝试了很多解决方案,但没有任何正确的结果是因为JSON响应。我也找不到很好的例子和教程。而且我是新的,正如我对php所说的,所以我害怕尝试复杂的场景

这里是php代码

这是我的配置文件

db_config.php

<?php

define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "localhost"); // db server
?>

这是连接文件

db_connect.php
<?php


class DB_CONNECT {

    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }

    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }

    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';

        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

        // returing connection cursor
        return $con;
    }

    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }

}

?>

get_all_products.php

<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT *FROM products") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["products"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $product = array();
        $product["pid"] = $row["pid"];
        $product["name"] = $row["name"];
        $product["price"] = $row["price"];
        $product["created_at"] = $row["created_at"];
        $product["updated_at"] = $row["updated_at"];

        // push single product into final response array
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}
?>

我知道对于有经验的人来说很容易,但我对此感到困惑。请帮忙,因为我的截止日期很紧迫,现在没有时间进行更深入的搜索。谢谢

**如果我发布我所做的事情会有帮助吗?出于空间原因我没有发布它**s

编辑 这就是我迄今为止所做的任何想法?

$db = new PDO("mysql:host=$dbhost;dbname=$dbname;", $dbuser, $dbpass);
$query = "Select * FROM products";


//execute query

try {

    $stmt   = $db->prepare($query);
    $result = $stmt->execute(HAVE NO IDEA!!!!);
}

catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error!";
    die(json_encode($response));

}




$rows = $stmt->fetchAll();
if ($rows) {
    $response["success"] = 1;
    $response["message"] = "Post Available!";
    $response["posts"]   = array();


    foreach ($rows as $row) {
        $post             = array();
        $post["pid"] = $row["pid"];
        $post["name"]    = $row["name"];
        $post["price"]  = $row["price"];


        //update our repsonse JSON data
        array_push($response["posts"], $post);

    }



    // echoing JSON response
    echo json_encode($response);

} else {

    $response["success"] = 0;
    $response["message"] = "No Post Available!";
    die(json_encode($response));

}


?>

【问题讨论】:

  • 严格的截止日期,我非常了解这些。没有什么比最后一刻更重要的东西了。
  • 是的,我想我要疯了!!哈哈哈
  • 这是PDO with prepared statements的链接。
  • 你不使用execute() 对抗query,你使用它对抗prepared statements。所以在这种情况下,查询应该只是foreach($db-&gt;query($query) as $row): 你使用准备好的语句的原因是当你接受用户输入时。

标签: php android mysql json pdo


【解决方案1】:

试试这个方法:

<?php
$response = array()
try {
    //connection
    $db = new PDO("mysql:host=$dbhost;dbname=$dbname;", $dbuser, $dbpass);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //prepare
    $query = "Select * FROM products";
    $stmt   = $db->prepare($query);
    //get resutlt
    $result = $stmt->execute();
    if ($stmt->rowCount > 0) {
        $response["success"] = true;
        $response["message"] = "Post Available!";

        //populate post array
        while($row = $stmt->fetch()){
            $response["posts"][] = $row;
        }
    }else{
        $response["success"] = false;
        $response["message"] = "No Post Available!";    
    }
}

catch (PDOException $ex) {
    $response["success"] = false;
    $response["message"] = "Database Error!";  
}

echo json_encode($response);

?>

Prepared statements and stored procedures


使用获取所有:
$rows = $stmt->fetchAll();
var_dump($rows);
$response["posts"] = $rows;

【讨论】:

  • 谢谢,但我有一个警告:array_push() 期望参数 1 为数组,给定为空。有什么想法吗?
  • 改用$response['posts'][] = $row;
  • 好吧,你是最棒的!!!!!!它成功了!!!谢谢!!!我能帮个忙吗?你能解释一下while循环是如何工作的吗??
  • 当然,while 循环是使用一次提取一行,与 fetchAll 没有太大区别
  • "pid":"1", "0":"1", "name":"X-Men: Days of Future Past", "1":"X-Men: Days of未来过去”这是我的输出,是重复的。我只需要名称和 ID。有什么想法吗?
猜你喜欢
  • 2021-04-15
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 2011-10-29
  • 1970-01-01
相关资源
最近更新 更多