这是我将数据插入数据库表的代码,但我想抓取数据并将其显示在下面的div中:
<?php
// only proccss the form if $_POST isn't empty
if ( ! empty( $_POST ) ) {
// connect to MySQL
$mysqli = new mysqli( 'localhost', 'root', '', 'mydb' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// insert our data
$sql = "INSERT INTO table1 ( name, email ) VALUES ('{$mysqli->real_escape_string($_POST['name'])}', '{$mysqli->real_escape_string($_POST['email'])}' )";
$insert = $mysqli->query($sql);
// print response from MySQL
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_id}";
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
// close our connection
$mysqli->close();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input name="name" type="text">
<input name="email" type="email">
<input type="submit" value="Add">
</form>
Display each name and email here like:
<div class="name">Get Name Here from Database</div><div class="email">Get Email Here from Database</div>
上面的代码适用于发布但我希望这样做,每当我转到同一页面时,它必须在表单下方显示数据rom数据库。
答案 0 :(得分:0)
尝试使用绑定变量和预处理语句:
<?php
$mysqli = new mysqli("localhost", "user", "pass", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST['scriptname'])) {
$scriptname = $_POST['scriptname'];
$stmt = $mysqli->prepare("INSERT INTO appslist(listall) VALUES (?)");
$stmt->bind_param('s', $scriptname);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Script Name: <input type="text" name="scriptname">
<input type="submit">
</form>
输出继电器:
1 Row inserted.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php