我完全按照我们老师在线讲座的方式制作了一个函数。但它不起作用,错误消息首先说有一个变量丢失。所以我检查了它,在 w3schools 上他们说你需要连接作为变量和字符串。所以我添加了连接,但后来我得到一个错误,说变量 vas 未定义。我尝试将函数放在 php-document 中的不同位置,但我不知道如何解决这个问题,请帮忙?
我的代码(我删除了我的密码):
<?php
// A function to help prevent SQL Injection.
function preparePostData($value)
{
// Removes slashes (/) if the server automaticlly adds them.
if(get_magic_quotes_gpc()){
$value = stripslashes($value);
}
/* Adds quote marks if the value is not numeric or a numeric string.
mysqli_real_escape_string adds slashes (/) if there is any character thats not allowed
and then the text string will not be processed in MySQL. */
if(!is_numeric($value)){
$value = "'" . mysqli_real_escape_string($dbConn, $value) . "'";
}
return $value;
}
// If the submit button is set do this..
if(isset($_POST['saveNews'])){
// Connection to db
$dbConn = mysqli_connect("localhost","sabe0011","password","sabe0011");
// Check connection
if(mysqli_connect_errno($dbConn)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// SQL question
$insertSQL = "INSERT INTO News (NewsId, Headline, News, Date) VALUES ('NULL',".preparePostData($_POST['newsHeader']).",".preparePostData($_POST['news']).",".preparePostData($_POST['newsDate']).");";
if(mysqli_query($dbConn, $insertSQL)){
echo "Nyheter har sparats";
}
else{
echo "Följande fel uppstod " . mysqli_error() . ".";
}
}
// Connection to db
$dbConn = mysqli_connect("localhost","sabe0011","password","sabe0011");
$dbConn->set_charset("utf8");
// Check connection
if(mysqli_connect_errno($dbConn)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$newsSQL = mysqli_query($dbConn,"SELECT * FROM News ORDER BY Date;");
echo "<div>";
if(mysqli_num_rows($newsSQL) > 0)
{
while($rowNews = mysqli_fetch_array($newsSQL)){
echo '<h2>' . $rowNews["Headline"] . '</h2>' . '<time>' . $rowNews["Date"] . '</time>' . '<p>' . $rowNews["News"] . '</p>';
}
}
else{
echo "Inga nyheter hittades";
}
echo "</div>";
?>