dsstlsqt696435 2014-05-26 17:48
浏览 33
已采纳

使用循环PHP创建字符串SQL查询

Last night I was thinking in a code part that I don't have it automated... That's why I don't has it has a object... One line of code is what I need to make it to a object a use it for a any project.

What I want is:

  1. Create a dynamic variables with a loop. (This is done and is a good idea)
  2. Create a dynamic SQL query with the variables that was created dynamic (This is what I want to do)

Here we create a dynamic variables with a for loop:

    /* This variables has the inputs of an HTML
    * inputs are the name of a input, in this example there are 2, email and pass
    * inputs_val store the value of email and pass
    $inputs;
    $inputs_val;

    // Starting with an array        
    $arrayName = array();
    // Then with a for loop we fill the array
    for ($i=0; $i < count($inputs_val); $i++) {
                // While $i are less than 2 (email, pass) $i++
        $var_nom = $inputs[$i];
        $var_val = $inputs_val[$i];
        $arrayName[$i] = $var_val;
                // if we want to store the input name we use:
                // $arrayName[$var_nom] = $var_val;
    }

My question is here:

How you create an string SQL query looping the array?

for ($i=0; $i < count($arrayName); $i++) { 
     $query = "SELECT usr_email, usr_pass FROM tbl_usr WHERE usr_email='$arrayName[$i]' AND usr_pass='$arrayName[$i]' LIMIT 1;";
}

The error is there: usr_email='$arrayName[$i]' and usr_pass='$arrayName[$i]' Because when the loop start with 0 is OK for usr_email, but not for usr_pass and when the loop pass again is OK for usr_pass but not for usr_email...

I try with a $i2 = $i+1; but also doesn't work.

Suggest and ideas?

  • 写回答

1条回答 默认 最新

  • dongmi4734 2014-05-26 21:26
    关注

    $arrayName[$i] can't be at the same time an email and a password. That's why it didn't work.

    If I well understand what you want, you can do something like that :

    $inputs;
    $inputs_val;
    $arrayName = array();
    for ($i = 0 ; $i < count($inputs_val) ; i++)
      $arrayName[$inputs[$i]][] = $inputs_val[$i];
    

    And then (with $inputs containing "user_email" and "user_pass") :

    for ($i=0; $i < count($arrayName['usr_email']); $i++) { 
         $query = "SELECT usr_email, usr_pass FROM tbl_usr WHERE usr_email='$arrayName['user_email'][$i]' AND usr_pass='$arrayName['user_pass'][$i]' LIMIT 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系统的像差计算