dongyaobo9081 2015-11-06 06:21
浏览 49
已采纳

SQL查询通过PHP post方法从多列中选择数据

I am new to web development. I am trying to implement a database-driven web server using Apache+PHP+SQLite. Using the post method, I try to pass the input values on the html page to the web server as an SQL query to retrieve data inside the database.

Problem description: Let's say there is a table (named my_table) in my database, having 3 columns, a1, a2 and a3. In the php file, there are 3 input values specified by the end-user, say $v1, $v2 and $v3. The values of $v1, $v2 and $v3 will be matched with patterns in a1, a2 and a3 so that the matched data rows will be retrieved. $v1, $v2 or $v3 can be an empty string, depending on the queries by the user. Formally speaking, if $v1='', $v2='' and $v3='', all of the data in my_table will be retrieved; if $v1='v1_value', $v2='' and $v3='', the data where column a1 has pattern v1_value will be retrieved.

My HTML form tag

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <table>
        <tr><td>Item1: </td><td><input type="text" name="v1"></td></tr>
        <tr><td>Item2: </td><td><input type="text" name="v2"></td></tr>
        <tr><td>Item3: </td><td><input type="text" name="v3"></td>
    </table>
    <input type="submit", name="submit" value="Submit">
</form>

My PHP code

$v1 = $_POST['v1']; 
$v2 = $_POST['v2'];
$v3 = $_POST['v3'];

And I am stuck at here...

$query = "SELECT * FROM my_table WHERE <A_PROPER_CONDITION_STATEMENT>"

That is, how to have a query to retrieve data as I want.

Hope I describe clearly. Thanks for help.

  • 写回答

1条回答 默认 最新

  • doujiazong0322 2015-11-06 06:30
    关注

    Try this code :-

    $query = "SELECT * FROM my_table WHERE 1=1 ";
    
    if(isset($_POST['v1']))
    $query .=" and  a1=".$_POST['v1'];
    
    if(isset($_POST['v2']))
    $query .=" and  a2=".$_POST['v2'];
    
    if(isset($_POST['v3']))
    $query .=" and  a3=".$_POST['v3'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败