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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化