我正在尝试使用mysqli向数据库插入多行,但它无效......
注意:我的目标是在图片上传成功后将文本和文件字段名称一起插入数据库。有什么想法吗?
这是html表单......
<form action="send.php" method="post">
First Name:<input type="text" name="fname" required><br>
Last Name:<input type="text" name="lname" required><br>
Age:<input type="text" name="age" required><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
这是我在send.php中的内容....当我尝试将图像路径插入数据库时它可以工作,但是当我从第一个表单中包含文本字段名称时它不起作用..
// your save code goes here
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2097152)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "";
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo "<font size='4' color='red'><b>We are sorry, the file you trying to upload already exists.</b></font>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"images/" . $_FILES["file"]["name"]);
$sub= 1;
$mysqli = new mysqli("localhost", "root", "", "simple_login");
// TODO - Check that connection was successful.
$photo= "images/" . $_FILES["file"]["name"];
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$age =$_POST["age"];
$stmt = $mysqli->prepare("INSERT INTO test (photo, Firstname, Lastname, Age) VALUES (?, ?, ?, ?)");
// TODO check that $stmt creation succeeded
// "s" means the database expects a string
$stmt->bind_param("s", $photo, $fname, $lname, $age);
$stmt->execute();
$stmt->close();
$mysqli->close();
echo "<font size='7' color='white'><b> Success! Your photo has been uploaded.</b></font>";
}
}
}
else
{
echo "<font size='4' color='red'><b>We are sorry, the file you trying to upload is not an image or it exceeds 2MB in size.</b></font><br><font color='blue'><i>Only images under size of 2MB are allowed</i></font>.";
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="submited" value="true" />
<?php
ini_set( "display_errors", 0);
if($sub==0)
{
?>
<label for="file"><font size="5"><b>Choose Photo:</b></font></label>
<input id="shiny" type="file" name="file" onchange="file_selected = true;" required>
<input id="shiny" type="submit" value="Upload" name="submit">
<?php
}
?>
</form>
答案 0 :(得分:0)
我对你的布局感到有些困惑。您有两个单独的表单,一个用于文本输入,另一个用于图像?
因此,只插入图像路径的值。图片已上传,但值为$ _POST ['fname'],$ _POST ['lname']&amp; $ _POST ['age']未设置。
你应该以一种形式制作并提交。
答案 1 :(得分:0)
$ stmt-&gt; bind_param(“s”,$ photo,$ fname,$ lname,$ age);
数据库列中的每个文本字段
$ stmt-&gt; bind_param(“ssss”,$ photo,$ fname,$ lname,$ age);
同一自己的数据库列中的所有文本字段
$ stmt-&gt; bind_param(“s”,$ photo。','$ fname。','。$ lname。','。$ age);
bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
参数类型:
*使用$_POST
检查var_dump($_POST)
以查看数据是否正确。