我需要做一个学校的分配,我遇到了很少的问题,但我不明白为什么下面的代码给表中的空值。只插入NOW() 表,否则它会显示Query Empty或类似的东西。我在不同的页面和不同的表格上有相同的代码,它就像一个魅力。
此致 沃纳。
<?php
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$pnimi =$_REQUEST['pitsa_nimi'];
$id =$_REQUEST['pitsatyybinimi'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO tellimused_pitsad '.
'(pitsa_nimi,aeg,toidutyybi_id)'.
"VALUES ( '$pnimi', NOW(), '$id' )";
mysql_select_db('carl.reinomagi');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo mysql_error();
echo "Entered data successfully\n";
mysql_close($conn);
header("location:tellimine.php");
&GT;
这是上一页(订购)代码:
<?php
$tulemus = mysql_query("SELECT * FROM pitsad, pitsatyybid WHERE pitsad.toidutyybi_id = pitsatyybid.id", $dbhandle);
while ($row = mysql_fetch_assoc($tulemus))
{
?>
<tr><form action="telli.php">
<td><? echo $row['pitsa_nimi']; ?></td>
<td><? echo $row['hind']; ?></td>
<td><? echo $row['valmimisaeg']; ?> Minutit</td>
<td><? echo $row['pitsatyybinimi']; ?></td>
<td>
<input type="submit" value="TELLI"/>
</form></td>
</tr>
<?php
}
?>
</table>
答案 0 :(得分:0)
Please, don't use
mysql_*
functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。
这是使用PDO的更好示例。此代码对SQL注入是完全安全的,并且优于使用mysql_*
函数。
请务必阅读评论并理解代码。
<?php
# Database Connection #
try {
$conn = new PDO("mysql:host=localhost;dbname=carl.reinomagi", "root", ""); //Please consider having different credentials.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Throw Exceptions on errors - This disables the need to check for errors, see the catch block below.
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //True prepared statements.
## Prepreations ##
$pnimi = $_POST["pitsa_nimi"];
$id = $_POST["pitsatyybinimi"]; //Please use $_POST or $_GET rather than $_REQUEST
## Data validation ##
if (empty($pnimi) || empty($id)) {
//One of the variables is empty, return an error to the user.
}
//Few things about this:
//Note the `backticks` around table and column names. This helps readability.
//Also note the placeholders :pnimi and :id, those placeholders for the prepared statement.
$query = "INSERT INTO `tellimused_pitsad` (`pitsa_nimi`, `aeg`, `toibutyybi_id`) VALUES (:pnimi, NOW(), :id);";
$statement = $stmt->prepare($query);
$statement->bindValue(":pnimi", $pnimi); //Bind the values to the placeholders
$statement->bindValue("id", $id);
$statement->execute();
header("Location: tellimine.php");
}
catch (PDOException $e) {
echo "An error has occured! " . $e->getMessage(); //Echo a generic error to all mysql error messages.
}