尝试仅将一列发布到数据库中 [英] Trying to post only one single column into database
本文介绍了尝试仅将一列发布到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我将数据插入数据库表的代码,但我想抓取数据并将其显示在下面的 div 中:
Here is my code that inserts data into a database table, but I want grab data and display it inside those div below:
<?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 数据库.
The code above works on posting but I want to make it like, whenever I go to same page it must display that data rom database below the form.
推荐答案
尝试使用绑定变量和准备好的语句:
Try to use binds variables and prepared statements:
<?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
这篇关于尝试仅将一列发布到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文