【问题标题】:PHP mysql query x=$variablePHP mysql 查询 x=$variable
【发布时间】:2015-12-03 19:31:57
【问题描述】:

如何将 $country 发送到第二个代码(从 country_name='$country' 的国家中选择 emr_value)我不知道为什么 $country = "" 或 null 请帮助

谢谢

  <?php

 $servername = "localhost";
 $username = "root";
 $password = "root";
 $dbname = "db";
global $country;
// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
 // Check connection
 if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
 }

 $sql = "SELECT meta_value FROM `wp_usermeta` where user_id=$user_id and meta_key='custom_field_6' ";
 $result = $conn->query($sql);



 if ($result->num_rows > 0) {
    // output data of each row
     while($row = $result->fetch_assoc()) {

    $country = $row["meta_value"];
    echo $country;


     }
 } else {
     echo "0 results";
 }
$conn->close();

?>

第二个代码(这里我想显示这个查询的数据(select emr_value from countries where country_name='$country'))

<?php

 $servername = "localhost";
 $username = "root";
 $password = "root";
 $dbname = "db";
global $country;
// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
 // Check connection
 if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
 }

 $sql = "select emr_value from countries where country_name='$country'";

 $result = $conn->query($sql);


     while($row = $result->fetch_assoc()) {

    $emr_value = $row["emr_value"];
    echo "<h1>EMR : " . $emr_value . "</h1>";   
}
$conn->close();

?>

【问题讨论】:

  • 将第一个文件包含到第二个文件中并使用变量。并且不需要在那里指定连接和全局变量。它应该可以工作。
  • 为什么有 2 个文件而不是 1 个?
  • 它只有一页,我怎么能解决它,当 echo sql = select emr_value from countries where country_name=' Jordan' 时,我看到了这个问题,问题是变量前的空格 - '乔丹的
  • 使用...where country_name =trim($country) 它将查询为:... where country_name = 'Jordan',变量值中没有前导或尾随空格。如果它们都在同一个文件中,则不需要include

标签: mysql


【解决方案1】:

也许你应该只有一个代码:

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT meta_value FROM wp_usermeta WHERE user_id='$user_id' AND meta_key='custom_field_6'";
$result1 = $conn->query($sql);

if ($result1->num_rows > 0) {
    // output data of each row
    while ($row1 = $result1->fetch_assoc()) {
        $country = trim($row1["meta_value"]);
        $sql = "SELECT emr_value FROM countries WHERE country_name='$country'";
        $result2 = $conn->query($sql);

        while ($row2 = $result2->fetch_assoc()) {
            echo "<h1>EMR : " . $row2["emr_value"] . "</h1>"; 
        }
    }
} else {
    echo "0 results";
}

$conn->close();

?>

或者在一个代码中创建两个函数:一个返回 $country,另一个返回 emr_value。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多