dongzhuo3376 2016-12-05 00:29
浏览 43
已采纳

在mysqli_query中格式化

I am using PHP to execute a query to a database. I have been successful in executing many queries with the program but one recent one has given me trouble. The original SQL query is as follows:

SELECT Champion, RunnerUp
FROM playoffs
WHERE Champion = "Detroit Red Wings"
AND (RunnerUp = "Montreal Canadiens" OR RunnerUp = "New York Rangers");

This runs successfully and produces the correct output when used in HeidiSQL directly on the database. I tried implementing it in the program as follows, swapping out the actual team names for PHP variables:

$result = mysqli_query($link, "SELECT Champion, RunnerUp
                FROM playoffs
                WHERE Champion = '$champion'
                AND (RunnerUp = '$RunnerUp' OR RunnerUp = '$RunnerUp2')") ;

In this version, it seems that the embedded set of parenthesis is not being identified as such, instead appearing to be part of the quotation. This version produced no output.

I modified it as follows:

$result = mysqli_query($link, "SELECT Champion, RunnerUp
                FROM playoffs
                WHERE Champion = '$champion'
                AND RunnerUp = '$RunnerUp' OR RunnerUp = '$RunnerUp2'") ;

Removing the second set of parenthesis, it executes but does not produce the desired result because the logic reads differently, giving me tuples for whenever $champion and $RunnerUp match or whenever $RunnerUp2 is the runner-up. Is there anyway to execute this statement as I originally intended using PHP?

UPDATE: After putting the query into a variable as follows:

 $query = "SELECT Champion, RunnerUp
                FROM playoffs
                WHERE Champion = '$champion'
                AND (RunnerUp = '$RunnerUp' OR RunnerUp = '$RunnerUp2')";

and echoing it, I got the output

SELECT Champion, RunnerUp FROM playoffs WHERE Champion = '' AND (RunnerUp = 'Montreal Canadiens' OR RunnerUp = 'Toronto St. Patricks')

So it looks like for some reason, my champion variable never receives anything. This is because when calling it originally, it was called as 'Champion' instead of 'champion.'

  • 写回答

1条回答 默认 最新

  • dsogx84602 2016-12-05 00:52
    关注

    After finding out where I went wrong previously, it appears that this code:

    $query = "SELECT Champion, RunnerUp
                FROM playoffs
                WHERE Champion = '$champion'
                AND (RunnerUp = '$RunnerUp' OR RunnerUp = '$RunnerUp2')";
    

    will in fact work. Though, as mentioned in the comments above, it would be cleaner to add the query to a variable and call it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含