首先请原谅mysql_*的使用,我很感激它被贬值了,但由于完全荒谬的原因,我不得不在这个项目中使用它。
因此,我使用这个功能从数据库中填充了一个下拉菜单
func.php
function artistQuery(){
$myData = mysql_query("SELECT * FROM artists");
while ($record = mysql_fetch_array($myData)){
echo '<option value="' . $record['artistID'] . '">' . $record['artistFirst'] . ' ' . $record['artistSurname'] . '</option>';
}
它填充下拉菜单:
newprod.php
<h1>New Product Entry:</h1>
<form action="php/addproduct.php" method="_POST">
<p>Please select the artist:</p>
<select name="artist">
<?php artistQuery();
?>
</select>
</form>
因此,从我的函数来看,尽管显示了艺术家的名字和姓氏,但选项值实际上是艺术家ID。
然后我使用
addproduct.php
<?php
include_once 'php/dbconn.php';
connect();
$artist = $_POST['artist'];
$query = "INSERT INTO products ('artistID') VALUES ('$artist')";
//execute query
$result = mysql_query($query) or die("Error in Query. $query. " . mysql_error());
echo "$artist";
?>
将artistID写入数据库,除非它不是在写。
我认为问题出在newprod.php(中间代码块)中,没有将artistID分配给"artist"的名称。
任何和所有的帮助,从你们优秀的人将不胜感激。
编辑:缺少字母!
在addproduct.php中,尝试以下操作:
$query = "INSERT INTO products (artistID) VALUES ('$artist')";
不是引用的列名(错误):
$query = "INSERT INTO products ('artistID') VALUES ('$artist')";
MySQL列名既不能是单引号的'artistID',也不能像Access Database中那样是双引号的"artistID",也不能是[artistID]。它必须是裸名artistID,或者像一样反引号
`artistID`
当列名中有空格(如)时,它很有用
`Artist Name`
它应该是method="POST"
,而不是method="_POST"
。
_POST
无效,被浏览器忽略。然后浏览器将使用GET
作为方法,这是HTML表单的默认方法。
编辑:@jacouh的答案也是有效的,你必须同时做他和我的改变才能让它发挥作用。
为了避免一些sql注入,请尝试使用mysql_escape_string
$query = "INSERT INTO products ('artistID') VALUES ('".mysql_escape_string($artist)."')";
检查$artist是否有值,可能是因为为null而没有插入数据库。或者可能不是数据库所期望的值,比如artistID是一个整数,$artist实际上是一个字符串。
在选择框中,您应该给出一些类似的东西
<select name="artist">
<option value="artist"><?php artistQuery();?></option>
</select>