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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程