下午的天才,希望你能提供帮助。 这是插入表Twitch& amp;在我添加上传图片之前的鸟类,现在唯一有效的部分是图片上传。这是非常简单的代码,但无法解决为什么它没有添加。
另外,一旦工作,我如何从TWITCH表中获取自动增量ID。 提前致谢。
<?php
session_start();
include ('dbconnect.php');
//Set Variables from Form
$species =($_POST['Species']);
$age =($_POST['Age']);
$sex =($_POST['Sex']);
$location =($_POST['Location']);
$date_seen = date("Y-m-d");
$time_seen =($_POST['Time']);
$twitch =($_POST['Comments']);
//$twitch_id=(". mysql_insert_id()");
//Insert Into Birds table
$query1 = "INSERT INTO Birds (Species, Age, Sex, Location, Date_Seen, Time_Seen, Comments) VALUES
( '$species', '$age', '$sex', '$location', '$date_seen', '$time_seen', '$twitch')";
result1 = mysqli_query($conn, $query1);
//Insert into Twitch table
query2 = "INSERT INTO Twitch (Twitch_ID, Twitch) VALUES( 'NULL', '$twitch')";
$result2 = mysqli_query($conn, $query2);
// Validate and upload image file
if ( !preg_match( '/gif|png|x-png|jpeg/', $_FILES['userFile']['type']) ) {
die('<p>Only browser compatible images allowed</p></body></html>');
} else if ( strlen($_POST['altText']) < 9 ) {
die('<p>Please provide meaningful alternate text</p></body></html>');
} else if ( $_FILES['userFile']['size'] > 1116384 ) {
die('<p>Sorry file too large</p></body></html>');
// Connect to database
} else if ( !($conn=mysqli_connect($host, $username, $password)) ) {
die('<p>Error connecting to database</p></body></html>');
} else if ( !(mysqli_select_db($conn, $db_name)) ) {
die('<p>Error selecting database</p></body></html>');
// Copy image file into a variable
} else if ( !($handle = fopen ($_FILES['userFile']['tmp_name'], "r")) ) {
die('<p>Error opening temp file</p></body></html>');
} else if ( !($image = fread ($handle, filesize($_FILES['userFile']['tmp_name']))) ) {
die('<p>Error reading temp file</p></body></html>');
} else {
fclose ($handle);
// Commit image to the database
$image = mysqli_real_escape_string($conn, $image);
$alt = htmlentities($_POST['altText']);
$query3 = 'INSERT INTO Image (Image_Name, Image_Type, Description, Image) VALUES ("' . $_FILES['userFile']['type'] . '","' . $_FILES['userFile']['name'] . '","' . $alt . '","' . $image . '")';
if ( !(mysqli_query($conn, $query3)) ) {
die('<p>Error writing image to database</p></body></html>');
} else {
header ("Location: TwitchWall.php");
}
}
?>
答案 0 :(得分:0)
如果你正在使用'mysqli',请尝试:
$last_id = mysqli::$insert_id;
否则,使用'mysql',使用:
$last_id = mysql_insert_id();
虽然旧的'mysql'方法已弃用 见这里:http://php.net/manual/en/function.mysql-insert-id.php
答案 1 :(得分:0)
使用mysql_insert_id()获取插入的记录ID。但是不推荐使用mysql_ * all函数,因此请使用mysqli_insert_id()或PDO :: lastInsertId()。
答案 2 :(得分:0)
mysqli_insert_id()函数返回查询生成的ID,该查询在具有AUTO_INCREMENT属性的列的表上。如果最后一个查询不是INSERT或UPDATE语句,或者如果修改后的表没有具有AUTO_INCREMENT属性的列,则此函数将返回零。
面向对象的风格
$query = "INSERT INTO ...";
$con->query($query);
echo $con->insert_id;
程序风格
$query = "INSERT INTO ...";
mysqli_query($con, $query);
echo mysqli_insert_id($con);
答案 3 :(得分:0)
要获取最后一个自动插入的ID,您可以使用
mysqli_insert_id($conn);