我已经问了一个关于PDO user add records to database PDO的问题,现在我无法选择数据并将它们插入到html表单中,以便允许用户选择什么,从而将记录添加到数据库中表
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
try {
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to database<br />';
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<?php
if ($_GET['action'] == 'edit') {
//retrieve the record's information
$sth = $dbh->prepare = 'SELECT
nome, cognome, indirizzo, civico, citta,
prov
FROM
tagesroma
WHERE
id = ' . $_GET['id'];
$sth = $dbh->execute();
extract($sth = $dbh->fetch());
} else {
//set values to blank
$nome = '';
$cognome = '';
$indirizzo = '';
$civico = 0;
$citta = '';
$prov = '';
}
?>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo ucfirst($_GET['action']); ?> Tages</title>
<style type="text/css">
<!--
#error { background-color: #600; border: 1px solid #FF0; color: #FFF;
text-align: center; margin: 10px; padding: 10px; }
-->
</style>
</head>
<body>
<?php
if (isset($_GET['error']) && $_GET['error'] != '') {
echo '<div id="error">' . $_GET['error'] . '</div>';
}
?>
<form action="commit.php?action=<?php echo $_GET['action']; ?>&type=tages"
method="post" accept-charset="UTF-8">
<table>
<tr>
<td>Nome</td>
<td><input type="text" name="nome" value="<?php echo $nome; ?>"/></td>
</tr><tr>
<td>Cognome</td>
<td><select name="cognome"></td>
<?php
//seleziona il tipo di cognome
$sth = $dbh->prepare = 'SELECT
cognome
FROM
tagesroma';
$sth->execute();
//popola con i risultati
while ($row = $sth->fetch()) {
foreach ($dbh->$row as $value) {
if ($row['id'] == $cognome) {
echo '<option value="' . $row['id'] .
'" selected="selected">';
} else {
echo '<option value="' . $row['id'] . '">';
}
}
}
?>
</select></td>
</tr><tr>
<td colspan="2" style="text-align: center;">
<?php
if ($_GET['action'] == 'edit') {
echo '<input type="hidden" value="' . $_GET['id'] . '" name="id" />';
}
?>
<input type="submit" name="submit"
value="<?php echo ucfirst($_GET['action']); ?>" />
</td>
</tr>
</table>
</form>
</body>
</html>
我正在处理的错误如下:
Fatal error: Call to a member function execute() on a non-object on line 76
答案 0 :(得分:0)
您没有正确使用预准备语句。试试这个:
<?php
$id = $_GET['id'];
$sth = $dbh->prepare("SELECT
nome, cognome, indirizzo, civico, citta,
prov
FROM
tagesroma
WHERE
id = :id");
$sth->bindParam(":id",$id,PDO::PARAM_INT);
$sth->execute();
?>
答案 1 :(得分:0)
错误Call to a member function execute() on a non-object
表示代码的这个区域无效:
$sth = $dbh->prepare = 'SELECT
nome, cognome, indirizzo, civico, citta,
prov
FROM
tagesroma
WHERE
id = ' . $_GET['id'];
$sth = $dbh->execute();
正确的方法是:
$sth = $dbh->prepare("
SELECT nome, cognome, indirizzo, civico, citta, prov
FROM tagesroma
WHERE id = ?
");
$sth->execute(array($_GET['id']));
prepare()
是一个函数,所以用=
跟着它是没有意义的