dongqie4233 2016-12-02 13:39
浏览 68
已采纳

使用MySQL创建一个php变量

I have a Problem and I don't know how to solve it. I try to make a simple if statement with a php variable. The Variable contains a MySQL SELECT value.

$adminarray = $mysqli->query("SELECT admin FROM user WHERE name LIKE '$username'");

$currentuser = mysqli_fetch_row($adminarray);

$adm = $currentuser[0];


echo "<form action='?delete1' method='post' style='visibility:";if ($adm = 1){echo "block";}else{echo "hidden";}echo "'>

I try to hide the button for non admins ($adm = 0) but it is not working. The IF Statemant always returns a "true". even if $adm is 0.

I know the code isn't that good, but I'm still learning. So if you can give some tips :)

Thanks for answering

  • 写回答

2条回答 默认 最新

  • dougaicha5258 2016-12-02 13:44
    关注

    Firstly, use ternary operator for inline comperison and read about comparison operators in PHP

    Secondly, do not write a few strings that separated by semicolon together. Semicolon in PHP means end of instruction and it's better to write each in new line, so it will be easier to read and maintain the code

    Thirdly, always escape data in SQL queries and check type of variable before indexing it as array(is_array, isset)

    Finnaly, use IDE (PhpStorm, NetBeans etc) it will help you to prevent doing such mistakes

    $username = $mysqli->real_escape_string($username);
    $adminarray = $mysqli->query("SELECT admin FROM user WHERE name LIKE '$username'");
    
    $currentuser = mysqli_fetch_row($adminarray);
    
    $adm = is_array($currentuser) ? $currentuser[0] : null;
    $visibility = $adm == 1 ? "block" : "hidden";
    
    echo "<form action='?delete1' method='post' style='visibility:$visibility'>";
    

    It is also worth noting that prepared statements are preferable to plain SQL queries when you are using parameters. In that case code will look slightly different:

    $stmt = $mysqli->prepare("SELECT admin FROM user WHERE name LIKE ?");
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_row();
    $visibility = (is_array($row) && $row[0] == 1) ? "block" : "hidden";
    
    echo "<form action='?delete1' method='post' style='visibility:$visibility'>";
    

    More details about prepared statements you can find here: Prepared Statements

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算