PHP外部变量起反应

时间:2017-08-09 10:46:21

标签: javascript php mysql ajax reactjs

我知道如何将数据从PHP发送到react组件,但是如何将菜单中选择的id从react组件发送到PHP文件?

$.ajax({url: '/file.php', type: 'POST',
          dataType: 'json',
      success: response => {
        console.log(response)
      }});

在PHP文件中:

$testid= //how do i send a variable here
$results = $db->statement("SELECT * FROM tablename where id='testid");

echo json_encode($results);

2 个答案:

答案 0 :(得分:0)

$.ajax(
{
    url: '/file.php',
    type: 'POST',
    dataType: 'json',
    data: {
        'name': 'john'
    },
    success: response => {
        console.log(response)
    }
});

PHP文件:

$testid= $_POST["name"];
$results = $db->statement("SELECT * FROM tablename where id = $testid");

echo json_encode($results);
  

警告:您的SQL查询将无法进行SQL注入。 LEARN HOW TO PREVENT SQL INJECTION

答案 1 :(得分:0)

您需要通过JavaScript发送ID

$.ajax({url: '/file.php', data : {userId : ?} , type: 'POST', dataType: 'json',
           success: response => {
              console.log(response)
           }});

然后你需要从$_POST获取值并将其与查询

连接起来
$testid= $_POST["userId"];
$results = $db->statement("SELECT * FROM tablename where id = " . $testid);

但这可能导致 SQL注入