0
我是PHP的新手,我正在學習一個從mySQL數據庫表中獲取信息的教程,並輸出一個表單來創建新的表格行。出於某種原因,我無法弄清楚我的代碼出了什麼問題?當我刷新頁面時,該頁面是空白的,我一直在盯着這段代碼。有人知道我做錯了什麼嗎?數據庫連接沒問題,因爲它在另一個頁面上使用,我已經檢查過。如何通過PHP表單將數據發佈到mySQL數據庫?
我擁有的mySQL數據庫非常簡單,有1個表稱爲具有5個列(ID,用戶名,名字,姓氏,標題)的用戶,ID爲唯一字段。
<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST['delete']) && isset($_POST['ID']))
{
$id = get_post('ID');
$query = "DELETE FROM users WHERE ID='$id'";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br>" .
mysql_error() . "<br><br>";
}
if (isset($_POST['ID']) &&
isset($_POST['username']) &&
isset($_POST['firstName']) &&
isset($_POST['lastName']) &&
isset($_POST['title']))
{
$id = get_post('ID');
$username = get_post('username');
$firstName = get_post('firstName');
$lastName = get_post('lastName');
$title = get_post('title');
$query = "INSERT INTO users VALUES" .
"('$id', '$username', '$firstName', '$lastName', '$title')";
if (!mysql_query($query, $db_server))
echo "INSERT failed: $query<br>" .
mysql_error() . "<br><br>";
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
ID <input type="text" name="ID">
username <input type="text" name="username">
firstName <input type="text" name="firstName">
lastName <input type="text" name="lastName">
title <input type="text" name="title">
<input type="submit" value="ADD RECORD">
</pre></form>
_END;
$query = "SELECT * FROM users";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
ID $row[0]
username $row[1]
firstName $row[2]
lastName $row[3]
title $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="title" value="$row[4]">
<input type="submit" value="DELETE RECORD"></form>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
任何幫助將超級棒!
本教程是相當過時的 – Strawberry
聲明:此代碼是容易受到SQL注入。你也不應該使用已棄用的'mysql'-lib了。改爲使用'mysqli'或'PDO'。 – AbcAeffchen