从一个数据库中选择一个数组,并将其与另一个数据库的数组进行比较


Select an array from one databank and compare it to one from another databank

我知道标题不是最好的,但它以某种方式总结了问题:我运行了一个页面,客户可以在该页面上请求某个特定主题的导师。现在,我有一个数据库供我的导师使用,其中包含他们的特定主题,还有一个数据库用于接收客户的请求。我现在想做的是,编写一个SQL命令,将传入请求的主题与我导师的主题进行比较,这样教授该主题的老师在登录时就会看到请求。举个例子:母亲安妮塔请一位数学老师->发送请求。代码检查哪些老师教数学,并在这些老师登录时向他们显示请求。请记住,我是一个该死的初学者。

我目前的代码如下:

// Connect to the teacher databank and select the subjects of the teacher that has logged in
$connect = mysql_connect('xxx', 'xxx', 'xxx');
mysql_set_charset("utf8", $connect);
mysql_select_db('xxx');
$sql = "SELECT subjects FROM teachers WHERE teacher LIKE '%". $_SESSION['user'] ."%'" ;
$erg = mysql_query(@$sql);
if (false === $erg) {
die (mysql_error());
}
$speicher = mysql_fetch_array($erg, MYSQL_ASSOC);
print_r ($speicher);  
// Until here it functions and the array ($speicher) contains the subjects of the teacher
// Now connect to the other Databank (with the requests)
$connect = mysql_connect('xxx', 'xxx', 'xxx');
mysql_set_charset("utf8", $connect);
mysql_select_db('xxx');
$sql = "SELECT street, class, subject, school FROM requests WHERE subject IN ('%s')";
$inElems = array_map(function($elm) {
return "'" . mysql_real_escape_string($elm) . "'";
}, $speicher);
$sql1 = sprintf($sql, join(",", $inElems));
echo $sql1;
// It correctly spills out the SELECT Query but it is wrong because of the '' around the subjects are missing -> see output
$erg = mysql_query($sql1);
if (false === $erg) {
die (mysql_error());
}
$content = mysql_fetch_array($erg, MYSQL_ASSOC);
print_r ($content);

输出:

SELECT street, class, subject, school FROM requests WHERE subject IN ("English, German, Mathematics")
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'English, German, Mathematics")' at line 1

所以我不知道如何设置它是正确的,目前它不起作用,因为主题之间缺少",但我不知道其他方法。我是个初学者。我知道,我真的需要把它改成MySQLi,一旦这个问题解决了,我就会这么做。

不能只使用join来实现这一点。首先,你必须在项目中添加Apostrophes

$inElems = array_map(function($elm) { 
    return "'" . mysql_real_escape_string($elm) . "'";
}, $speicher);

mysql_real_sescape_string用于防止SQL注入。这不是推荐的方法,但让我们保持简单。

然后,使用数组加入

$sql1 = sprintf($sql, join(",", $inElems));

正如Oldskool所提到的那样,mysql_*函数迟早会被弃用,我建议您使用PDO而不是

如果有效,请告诉我:)

干杯