简体   繁体   中英

MySQL query updating depending on $_POST values

I am having trouble thinking out a good way to update my query depending on user $_POST values. Basically I have user management search button, where site administrator can search for his sites users. In my example:

<div id="website_user_management_search_left">
<div id="website_user_management_search_left_leftside">
    <p>Name:</p>
    <p>Surname:</p>
    <p>Telephone:</p>
    <p>Group:</p>
    <p>Discount group:</p>
</div>
<div id="website_user_management_search_left_rightside">
    <input type="text" name="#" value="#" id="userSearch_name">
    <input type="text" name="#" value="#" id="userSearch_surname">
    <input type="text" name="#" value="#">
    <input type="text" name="#" value="#">
    <input type="text" name="#" value="#">
    <input type="submit" id="button_adminUserSearch" value="Search">
</div>

Then after pressing "Search" button AJAX sends request to retrieve results, but how can I handle this dynamic query? For example - if user just presses "Search" query would look like:

mysqli_query($dbconnect,"SELECT * FROM accounts");

For example - if user specifys $_POST["name"] value, query would look like:

mysqli_query($dbconnect,"SELECT * FROM accounts WHERE name='".$_POST["name"]."'");

Problem is - how can I efficiently handle this kind of query? It would be dumb to check which values is "isSet" and then make tons of query cases. I hope you understood my problem and can help out with it, because it`s kinda hard to explain it.

Maybe you're looking for something like it :

if(empty($_POST['name'])) {
    $name = null;
} else $name = $_POST['name'];

Then in your statement, your condition would be :

WHERE (name=:name OR :name is null)

If name isset, it will search for this name, else it will return true and query will not be affected

You could do something like that:

mysqli_query($dbconnect,"SELECT * FROM accounts WHERE name LIKE'%".$_POST["name"]."%'");

But there are two little problems: You don't have escaped your user input data with mysqli_escape_string() and: You shouldn't do that. A better way would be to add a where clause only, if name POST data is set:

$where = '';
if ($_POST['name']) {
  $where = ' WHERE name = '".$name."'"';
}
mysqli_query($dbconnect,"SELECT * FROM accounts" . $where);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM