douhan8581 2014-09-18 22:45
浏览 50
已采纳

将PHP文件转换为PDO [关闭]

i am beginer to php and i need your help.i want to make the following code to PDO to have a json output for an android app i am trying to bulit.I tryed a lot of solution but nothing correct came because of the JSON responce.I couldn also find good example and tutorials.Also i am new as i said with php so i am afraid to try complicated scenarios

here is the php code

This is my Config file

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

This is connection file

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);
}
?>

I know is very easy for someone with experience but i am strungle with it.please help because i have a strick deadline and no time now for deaper search.Thank you

**Would it be helpfull if i post what i have done?I didnt post it for space reason**s

EDIT THIS IS WHAT I HAVE DONE SO FAR ANY IDEAS?

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

}


?>
  • 写回答

1条回答 默认 最新

  • douwu8060 2014-09-19 01:03
    关注

    Try this approach:

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


    using fetch all:
    $rows = $stmt->fetchAll();
    var_dump($rows);
    $response["posts"] = $rows;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vc6.0中想运行代码的时候总是提示无法打开文件是怎么回事
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题