使用通过.load()传递给PHP的数据来执行数据库查询

时间:2022-09-26 08:47:55

I am trying to get an AJAX query to work. Im passing data to a PHP script using:

我试图让AJAX查询工作。我使用以下方法将数据传递给PHP脚本:

$(".example").click(function(){
x = this.innerHTML;
$("#example").load("ajax.php",{"data":x});
});

If ajax.php just includes the following (did this as a test), everything is fine; I've passed JS data successfully to PHP.

如果ajax.php只包括以下内容(这是测试),一切都很好;我已成功将JS数据传递给PHP。

echo $_POST['data'];

My goal is to query my DB using $_POST['data'] though. As another test, I made sure the DB connection was all ok. The following works:

我的目标是使用$ _POST ['data']查询我的数据库。作为另一个测试,我确保数据库连接都没问题。以下作品:

$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=?");
$example->bind_param('s',$_SESSION['user_id']);
$example->execute();
$example->bind_result($x,$y,$z,$a);
while($example->fetch()){
echo '<h3>'.$x.'</h3>';
echo '<p>'.$y.'</p>';
echo '<p>'.$z.'</p>';
echo '<p>'.$a.'</p>';
}

When I amend the below lines however, nothing is returned from the script.

但是,当我修改下面的行时,脚本没有返回任何内容。

$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=? AND a=?");
$example->bind_param('ss',$_SESSION['user_id'],$_POST['data']);

The puzzling thing is that the data being passed from JS initially was obtained from the database. When I use alerts, the words are exactly the same as my my DB record.

令人费解的是,最初从JS传递的数据是从数据库中获得的。当我使用警报时,这些单词与我的DB记录完全相同。

Any suggestions? Could this be something to do with datatype? do I need to make sure $_POST['data'] is converted to a string somehow?

有什么建议?这可能与数据类型有关吗?我需要确保$ _POST ['data']以某种方式转换为字符串吗?

When I look in firebug, I see the following POST details ('Test Title' is the data used in my query)

当我查看firebug时,我看到以下POST详细信息('Test Title'是我的查询中使用的数据)

Parameters
data    Test Title

Source
data=+Test+Title

Do the + signs represent spaces? perhaps I need to trim a space from beginning of data?

+符号代表空格吗?也许我需要从数据开始修剪空间?

1 个解决方案

#1


0  

This was due to white space. Fixed with the following:

这是由于空白。修复了以下内容:

$(".example").click(function(){
y = this.innerHTML;
x = y.trim();
$("#example").load("ajax.php",{"data":x});
});

#1


0  

This was due to white space. Fixed with the following:

这是由于空白。修复了以下内容:

$(".example").click(function(){
y = this.innerHTML;
x = y.trim();
$("#example").load("ajax.php",{"data":x});
});