【问题标题】:msyql database selection based on if else statement and php variables基于if else语句和php变量的mysql数据库选择
【发布时间】:2015-02-20 22:01:31
【问题描述】:

让这个工作和语法有问题 - 我以前从来没有做过这样的事情,也没有写一些原始的东西。我有一个传递两个变量的 url。然后我在页面中获取这些变量。然后我想根据这些变量之一选择我连接到的 mysql 数据库。

变量:

$account_id=$_GET["reference"];

然后它选择连接到哪个数据库:

$link = mysql_connect('connect', 'user', 'pass');
if (!$link) {
     die('Not connected : ' . mysql_error());
 }

if ($item = "A"){
     $db_selected = mysql_select_db('A', $link);
     } elseif ($item = "B") {
    $db_selected = mysql_select_db('B', $link);
    } elseif (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
 }

它一直在选择项目 A。我无法让它选择 B 或给出错误。我哪里错了?

【问题讨论】:

  • 比较逻辑运算的值时,必须使用><=====!=!==。您正在使用单个等号,它不是用于比较而是用于赋值。参见手册:php.net/manual/en/language.operators.comparison.php
  • 那个^和$item应该是$account_id。就目前而言,$item 是未定义的。 This will tell you...
  • @ChrisBaker Stealth 编辑,正在进行中...
  • 希望对@ChrisBaker 的回答给予更多的赞誉,而不仅仅是点赞。
  • @ChrisBaker 我建议因为 OP 还邀请您提供答案,以便我们将其全部结束。问题是分配而不是比较。

标签: php mysql conditional-statements


【解决方案1】:

在比较逻辑运算的值时,您必须使用><=====!=!==。您使用的是单个等号,它不是用于比较而是用于赋值。

这就是你正在做的事情

$item = 'b';          // a single equals sign assigns a value
if ($item = 'a') {    // so in this line, we are not comparing but assigning!
    echo 'Item is a'; // this line will always be reached
} else {
    echo 'Item is b'; // this line will NEVER be reached
}
echo 'Item = '.$item; // will ALWAYS read "Item = a"

这就是你的本意

$item = 'b';           // a single equals sign assigns a value
if ($item == 'a') {    // double-equals compares value, with type juggling
    echo 'Item is a';  
} else {
    echo 'Item is b';  // now this line will be reached, because item != 'a'
}
echo 'Item = '.$item;  // will read "Item = b"


`==`  - value is equal, not necessarily the same type (1 == "1")
`!=`  - value is not equal, may or may not be the same type (2 != "3")
`===` - value is equal AND the same type (1 === 1)
`!==` - value is not the same type, or not the same value (2 !== "2")

文档

【讨论】:

  • 克里斯写得很好。
【解决方案2】:

使用 == 而不是 =

if ($item == "A"){
     $db_selected = mysql_select_db('A', $link);
     } elseif ($item == "B") {
    $db_selected = mysql_select_db('B', $link);
    } elseif (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
 }

【讨论】:

    猜你喜欢
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 2018-07-24
    • 2021-12-07
    相关资源
    最近更新 更多