我一直在修改我的PHP代码以将数据插入到SQL表中,而且我总是得到ERROR QUERYING DATABASE。这些值来自普通的HTML表单,然后当我点击提交(action = memberadd.php)时,我从下面的代码中收到错误消息。我错过了什么,却看不出它是什么????
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$industry = $_POST['industry'];//only showing one - need to fix
$profile_visibility = $_POST['profile_visibility'];
$position = $_POST['position'];
$status = $_POST['status'];
$profile_link = $_POST['profile_link'];
$skills = $_POST['skills'];
//connects and sends information to the database
$dbc = mysqli_connect('localhost', 'root', 'root', 'main') or die('Error connecting to MySQL server.');
//inserts data into the member_details table main db
$query = "INSERT INTO 'member_details' (first_name, last_name, city, state, country, industry, profile_visibility, position, status, profile_link, skills)
VALUES ('$first_name', '$last_name', '$city', '$state', '$country', '$industry', '$profile_visibility', '$position', '$status', '$profile_link', '$skills')";
$result = mysqli_query($dbc, $query) or die('Error querying database.');
mysqli_close($dbc);
echo '<h2>Here are your details.</h2>';
echo '<h3>First Name: '.$first_name.'<br />';
echo '<h3>Last Name: '.$last_name.'<br />';
echo 'City: '.$city.'<br />';
echo 'State: '.$state.'<br />';
echo 'Country: '.$country.'<br />';
echo 'Industry: '.$industry.'<br />';//only showing one - need to fix
echo 'Profile: '.$profile_visibility.'<br />';
echo 'Position: '.$position.'<br />';
echo 'Status: '.$status.'<br />';
echo 'Link: '.$profile_link.'<br />';
echo 'Skills: '.$skills.'<br /></h3>';
?>
答案 0 :(得分:2)
问题
由于@Fred -ii-有noted,问题在于INSERT
语句中的表名围绕引号。
$query = "INSERT INTO 'member_details' (first_name, ...
^ ^
解决方案
如果你想引用&#39;表格或列名称,您应该使用反引号,您可以在MySQL documentation page上阅读更多相关信息。
$query = "INSERT INTO `member_details` (first_name, ...
检测错误
要检查MySQLi数据库错误请求,可以使用一些方法来获取错误信息。可能最有用的是mysqli_error()
will give you an error string。
$result = mysqli_query($dbc, $query);
if(!$result)
{
printf("Errormessage: %s\n", mysqli_error($dbc));
}
作为@Fred -ii-还mentioned,您应该在开发新代码时正确使用错误报告。理想情况下,您应该在php.ini中配置它,但也可以通过将以下内容添加到页面顶部来轻松完成。
error_reporting(E_ALL);
ini_set('display_errors', 1);
最后,您对SQL Injection Attacks 持开放态度。您应该考虑使用prepared statements with MySQLi来帮助防止这种情况发生。
答案 1 :(得分:1)
你可以使用像...这样的mysql查询。
$query = "INSERT INTO `member_details` SET first_name = '".$first_name."', last_name = '".$last_name."', city = '".$city."', state = '".$state."', country = '".$country."', industry = '".$industry."', profile_visibility = '".$profile_visibility."', position = '".$position."', status = '".$status."', profile_link = '".$profile_link."', skills = '".$skills."'";