Php Mysql命令不会执行

时间:2015-02-15 02:17:11

标签: php html mysql pdo

我不能为我的生活理解如何做到这一点。我试图将$ vo对象的信息放入我的$ requete然后执行它,但我继续得到 Catchable致命错误:类Vo的对象无法转换为字符串

以下是代码:

<?php

class Dao{

function __construct(){


}


function createOrder($vo){

$server="localhost";
$user = 'root';
$pass = '';
$db   = 'test';

$db = new PDO("mysql:host=$server;dbname=$db", $user, $pass);

$name=$vo->name;

$requete=$db->prepare("INSERT INTO ha(name, address, city, country, phone, selection) VALUES ($vo->name, $vo->address, $vo->city, $vo->country, $vo->$phone, $vo->selection)";
$db->exec($requete)or die ("failure");
echo "success";


}
}

?>

3 个答案:

答案 0 :(得分:0)

尝试以下字符串:

$requete = $db-prepare("insert into ha (name,address,city,country,phone,selection) values ('$vo->name', '$vo->address', '$vo->city', '$vo->country', '$vo->$phone', '$vo->selection')");

您需要引用这些值。要明白为什么...... 让我们说用户的名字是:

George Johnson,Jr。

你能明白为什么需要引用这个吗?这是因为如果有一个逗号是名称的一部分,那么SQL语句就会被误解。

错:

  

价值(George Johnson,Jr.,123 Elm Street)

右:

  

价值(&#39; George Johnson,Jr。&#39;,&#39; 123 Elm Street&#39;)

答案 1 :(得分:0)

试试这个:

$requete=$db->prepare("INSERT INTO ha(`name`, `address`, `city`, `country`, `phone`, `selection`) VALUES ($vo->name, $vo->address, $vo->city, $vo->country, $vo->$phone, $vo->selection)";
$db->exec($requete)or die ("failure");

答案 2 :(得分:0)

更改您的代码并使用问号作为准备变量的占位符。并且您在预准备语句中有语法错误,您不能使用预准备语句并使用您的pdo执行准备好的语句$db->exec应该是$requete->execute

$name=$vo->name;
$address=$vo->address;
$city=$vo->city;
$country=$vo->country;
$phone=$vo->phone;
$selection = $vo->selection;

$requete =$db->prepare("INSERT INTO `ha`(`name`, `address`, `city`, `country`, `phone`, `selection`) VALUES (?,?, ?, ?, ?, ?)");
try {
 $requete->execute(array($name, $address, $city, $country, $phone, $selection));
} catch (Exception $ex) {
 echo $ex->getMessage();
 die();
}
相关问题