数据未使用PDO语句插入到mysql中

时间:2014-07-17 10:20:02

标签: php mysql sql pdo

我在使用PDO语句插入时遇到问题。我正在从mysql迁移到PDO语句。所以欢迎你的意见。这根本不是一个重复的问题。我已经检查了其他问题,但无法得到结果。所以,请不要将其标记为重复的问题。

<?php
class Stock{
    const DB_HOST = 'localhost';
    const DB_NAME = 'stock';
    const DB_USER = 'root';
    const DB_PASSWORD = '';

    private $conn = null;



    /**
    * Open the database connection
    */
    public function __construct(){
        // open database connection
        $connectionString = sprintf("mysql:host=%s;dbname=%s",
                        Stock::DB_HOST,
                        Stock::DB_NAME);
        try{
            $this->conn = new PDO($connectionString,
                        Stock::DB_USER,
                        Stock::DB_PASSWORD);
        }
        catch(PDOException $e){
            die($e->getMessage());
        }
    }//end of constructor

    public function insert_stock($stock_symbol,$stock_name,$no_of_trans,$max_price,$min_price,$closing_price,$total_shares,$amount,$previous_close,$difference){
        $data = array(
            ':stock_symbol'         => $stock_symbol,
            ':stock_name'           => $stock_name,
            ':no_of_trans'          => $no_of_trans,
            ':max_price'            => $max_price,
            ':min_price'            => $min_price,
            ':closing_price'        => $closing_price,
            ':total_shares'         => $total_shares,
            ':amount'               => $amount,
            ':previous_close'       => $previous_close,
            ':difference'           => $difference
        );
        $sql = 'INSERT INTO tbl_stock(stock_symbol,stock_name,no_of_trans,max_price,min_price.closing_price,total_shares,amount,previous_close,difference) 
                VALUES(:stock_symbol,:stock_name,:no_of_trans,:max_price,:min_price,:closing_price,:total_shares,:amount,:previous_close,:difference)';

        $q = $this->conn->prepare($sql);

        return $q->execute($data);

    }
}//end of class

$obj = new Stock;
if($obj->insert_stock('TES','Testing',5,500,600,200,2000,200000,600,10)!= false){
    echo 'One row added sucessfully';
}
else{
    echo 'Error adding the task';
}
?>

我的tbl_stock表格中还有auto_increment的ID。

1 个答案:

答案 0 :(得分:0)

连接字符串中有拼写错误:

    $connectionString = sprintf("mysql:host=%s;dbaname=%s",
                    Stock::DB_HOST,              ^
                    Stock::DB_NAME);

替换为:

    $connectionString = sprintf("mysql:host=%s;dbname=%s",
                    Stock::DB_HOST,              
                    Stock::DB_NAME);