查询如下
SELECT `sID` FROM `subscribers` where `Email` LIKE '%xxx@xxx.com%'
和
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
$hostname = "dd";
$username = "cc";
$password = "aa";
$dbName = "bb";
$conn = new mysqli($hostname, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn -> select_db("$dbName") or die( "Unable to select database");
check_subscriber($email, $first, $last, $company, $tablename);
function check_subscriber($email, $first, $last, $company, $tablename)
{
global $wpdb;
$emailid=mysql_real_escape_string($email);
$subscribercheck = "SELECT `sID` FROM `$tablename` where `Email` LIKE '%$emailid%'";
$subscriber_exists = "";
$subscriber_exists = $wpdb -> get_results($wpdb->prepare("$subscribercheck",object));
var_dump($subscriber_exists);
if(count($subscriber_exists)>0){
foreach ($subscriber_exists as $subs)
{
echo $sid = $subs-> sID;
}
}
else {
$wpdb -> insert('subscribers', array(
'First Name' => $first,
'Last Name' => $last,
'Company' => $company,
'Email' => $email,
'Date' => date("Y-m-d H:i:s"),
));
}
}
var_dump = NULL
我尝试在我们的数据库中运行查询并且它有效,但它似乎没有在这里运行。请帮忙!
定义每个变量。 var_dump = NULL
所以它转到"else"
条款,其中wpdb -> Insert
发生并且有效。
$subscriber_exists = $wpdb -> get_results($wpdb->prepare("$subscribercheck",object));
但是,即使我可以在我们的数据库中运行它,也不会给我任何价值。
答案 0 :(得分:1)
以下是我发现的问题:
wp-config.php
为您设置了此连接。删除用于连接的代码段,并使用$wpdb
对象运行查询。$wpdb->prepare()
,但未正确设置必要的参数。如果您想使用预准备语句,您需要先了解它们的工作原理read here 这就是我重做代码的方式:
function check_subscriber($email, $first, $last, $company, $tablename) {
global $wpdb;
$email = $wpdb->esc_like($email);
$query = "SELECT `sID` FROM `$tablename` where `Email` LIKE '%$email%'";
$subscribers = $wpdb->get_results($query, object);
if (count($subscribers) > 0) {
foreach ($subscribers as $subs) {
echo $sid = $subs->sID;
}
} else {
$wpdb->insert('subscribers', array(
'First Name' => $first,
'Last Name' => $last,
'Company' => $company,
'Email' => $email,
'Date' => date("Y-m-d H:i:s"),
));
}
}
但是,如果您真的想使用预准备语句,请使用:
function check_subscriber($email, $first, $last, $company, $tablename) {
global $wpdb;
$query = "SELECT `sID` FROM `$tablename` where `Email` LIKE %s";
$like_email = '%' . $wpdb->esc_like($email) . '%';
$subscribers = $wpdb->get_results(
$wpdb->prepare($query, $like_email),
object
);
if (count($subscribers) > 0) {
foreach ($subscribers as $subs) {
echo $sid = $subs->sID;
}
} else {
$wpdb->insert('subscribers', array(
'First Name' => $first,
'Last Name' => $last,
'Company' => $company,
'Email' => $email,
'Date' => date("Y-m-d H:i:s"),
));
}
}