【发布时间】:2018-09-28 02:08:16
【问题描述】:
我在 PHP 中编写了以下函数,其中包含 mysqli_query,它运行时没有任何错误或异常。但是,INSERT INTO 语句或$insert 变量似乎没有按预期工作,我无法弄清楚。我意识到只发布部分代码可能很难确定它为什么不工作,但我真的在寻找确认这个函数没有错误。
我需要为每个提供的网址使用mysqli_real_escape_string 吗?我尝试将$website 更改为$_website 以解决此问题,但它什么也没返回。
只是想弄清楚我在这里是否做错了什么会阻止 SQL 查询工作。它不会返回导致难以调试的错误。提前致谢!
$jp = mysqli_connect("localhost", "myuser", "password", "mydatabase");
if (!$jp) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
function create_distributor( $new_user_id ) {
$errors = new WP_Error();
$error=false;
$errorMsg='';
$logo=true;
$name=addslashes(htmlentities($_REQUEST['name']));
$contact=addslashes(htmlentities($_REQUEST['contact_info']));
$user_info = get_userdata( $new_user_id );
$website = $_POST['website'];
if (stripos($website, "http://") !== 0) //doesn't start with http:// ? , then add it
$website = "http://" . $website;
// $_website = mysqli_real_escape_string($jp, $website); // THIS DOESNT RETURN ANYTHING
$subdir = $user_info->user_nicename; // use nicename because user_login is obfuscated as unverified
$distribpath = 'http://ghq.com/dhdq/'.$subdir;
$ga_code = 'UA-15331916-1'; //default GA code
$logo = 'http://ghq.com/wp-content/themes/CAG/img/ghlogo.jpg'; //default png logo
if(!isset($_REQUEST['name']) || $_REQUEST['name']=='')
{
$error=true;
$errors->add('Distributor Name is required', __('<strong>ERROR</strong>:Distrubutor\'s name was not provided.'));
}
if($error)
{
return($errorMsg);
}
$insert="INSERT INTO distributor (id, name, contact, logo, path, subdir, website, ga_code) VALUES ('".$new_user_id."','".$name."','".$contact."','".$logo."','".$distribpath."','".$subdir."','".$website."','".$ga_code."')";
// var_dump($insert);
// The var_dump print out above is the following SQL Command which if copied and pasted
in phpmyadmin works fine: string(252) "INSERT INTO distributor (id, name, contact,
logo, path, subdir, website, ga_code) VALUES ('1748','test24','','http://ghq.com/wp-content/themes/CAG/img/ghlogo.jpg',
'http://ghq.com/dhdq/test24','test24','','UA-15331916-1')"
mysqli_query($jp, $insert);
if ( false===$insert ) {
printf("error: %s\n", mysqli_error($jp));
}
else {
echo 'done.';
}
if($error)
{
return $errors;
}
else
{
return($id);
}
}
【问题讨论】:
-
尝试在查询中的字段名称周围加上反引号。
-
我尝试过使用反引号和不带反引号的字段名称。它们关闭的原因是,当您将查询粘贴到 myphpadmin 时,它会引发错误。我删除了它们,所以如果我在 phpmyadmin 中运行它,这个查询将完全按照它应该执行的方式执行。奇怪的是它可以在 phpmyadmin 中工作,但不是在这里
-
嗯,这是一个调试起点——如果你从代码中回显 SQL 并在 PHPmyadmin 中使用它并且它可以工作,那么你知道你的 SQL 可能没问题。检查错误日志,如果没有,那么很可能是代码中的逻辑。此外,您能否扩展“插入似乎不起作用” - 以什么方式?什么也没做?也只是为了确保您可以尝试输出 sql 错误(例如
mysqli_error()只是为了确保您的 SQL 和查询正常
标签: php mysql wordpress mysqli