MySQL query updating depending on $_POST values - php

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);

Related

php searching in more than one column mysql

I am trying to make a code to search for data in more than one column , the code works only if I search in one column. when I tried to search in two columns it says that nothing is found in the database.
<form action="" method="post">
<input type="text" name="param" >
<input type="submit" name="submit" value="search">
</form>
if (isset($_POST['param'])) {
$param= trim ($_POST['param']);
$result = "SELECT * FROM table WHERE student_Name LIKE '%$param%' AND course_name LIKE '%$param%'";
I think you should use OR unless you want to check the 2 columns with the same parameter.
$result = "SELECT * FROM thecars WHERE student_Name LIKE '%$param%' OR course_name LIKE '%$param%'";
Also, this is very open to SQL injection. Sanitize your input before you pass it to the query.
You could do a concat and search via that.
$result = "SELECT * FROM thecars WHERE CONCAT(`student_Name`, `course_name`) AS `search`LIKE '%$param%'";
Your using the same $param variable to search on both columns. If your searching for 2 separate values provide a form that supports inputting 2 values. And then handle such input properly in your query formation.
<form action="" method="post">
<input type="text" name="param1" >
<input type="text" name="param2" >
<input type="submit" name="submit" value="search">
</form>
if (isset($_POST['param1']) || isset($_POST['param2'])) {
$param1 = trim ($_POST['param1']);
$param2 = trim ($_POST['param2']);
$result = "SELECT * FROM thecars WHERE student_Name LIKE '%$param1%' AND course_name LIKE '%$param2%'";
Also change your column aggregation in where clause to OR as suggested by others if your searching for similar outcome.

Best Way to Post Data from Large Forms & Hold Data in Inputs after Errors

This is a "best practice"/"most efficient" question. I have a large form (20+ fields). Form post into one large MySQL table.
No I can't break up the form and no, I can't break up the table (its being used to hold measurements); used by admin sales reps. Also, I don't want to use Javascript.
I know I can do this:
HTML
<form action="etc.php" method="post">
<input type="text" name="neck" value="">
<input type="text" name="arm" value="">
<input type="text" name="back" value="">
<input type="text" name="chest" value="">
<input type="text" name="legs" value="">
<submit button>
PHP
<?
$_POST['neck'];
$_POST['back'];
$_POST['arm'];
$_POST['chest'];
$_POST['legs'];
$postMeasurements = "INSERT INTO measurements (etc, etc, etc,) VALUES (etc, etc, etc) WHERE etc='etc'; query ($postMeasurements);
?>
But is there a faster way? Instead of having to declare each individual post, simply just run a loop that takes all the data post and inserts into the table. Even if the data has be in the same order of the columns of the table or if the input names have to be the same as the table column names is fine by me; I am just getting tired have to keep writing all these $_POST variables into.
Second question: What is the best way to hold this data in case of an error? As it stands now, I hold everything in $_SESSION (one session variable for each input), then redirect back to the form page if there is an error with an error message. then echo each $_SESSION variables as that inputs value.
Thanks,
if the fields as the exact names as the field names. post can only have the fields and nothing else
//if $_POST has the form then, also this is very unsafe because there is no injection prevention too
$sql = "INSERT INTO table (" . implode(",", array_keys($_POST)) . ")"
. "VALUES ('" . implode("','", array_values($_POST)) . "')";
You can directly use $_POST['foo'] inside your query, and need not declare :) .
holding the data could be in session, or inline cache, if you have huge data, its better to use some cache in server, and onload of the form, it retrieves the data from server based on SESSION_ID
Have the page post to itself.
Then do something like this:
if($_SERVER["REQUEST_METHOD"] == "POST"){
// validate and insert post data
header("Location: $successUrl");
exit();
}
?>
<form action="etc.php" method="post">
<input type="text" name="neck" value="<?= $_POST["neck"]?>">
<input type="text" name="arm" value="<?= $_POST["arm"] ?>">
....

how to update sql table with a variable number of fields in the form php

I have a variable number of fields in a form.
The number of text fields are defined by the user with a function in jquery, but the final code of the form (example) is this:
<form id='form_educ' name='form_educ' method='post' action='form/educ.php'>
<div id='educ'>
<input type='text' name='date1' id='date1'/>
<input type='text' name='date2' id='date2'/>
<input type='text' name='date3' id='date3'/>
<input type='text' name='date4' id='date4'/>
....
</div>
<input type='submit' name='form_educ' value='Refresh'/>
</form>
These text fields when added by the user is create a sql INSERT TO (in another file):
$date = clean($_GET['date']);
"INSERT INTO educ (index_of_form, date, email) VALUES('$index', '', '" .mysql_real_escape_string($_SESSION['SESS_EMAIL']). "')";
$date is date1, or date2, or date3 or date4 (example).
Now in the file educ.php I want to update all text fields in the mysql database.
Usually it is a
$example = clean($ _POST ['example']);
I can do an update in the table and is resolved.
But in my case how can I get all the values โ€‹โ€‹of the text field on the form and set the $_POST var if the number of fields is variable (could be date1, date2, date3, date4)?
I can think of no reason why form field name should be a unknown variable. Unless you're dealing with repeatable fields, in which case you would use an array like dates[], and you'd know what to expect in the process script.
For additional info see for example: http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/
Word of warning for future. When you make the field repeatable, allow users also to delete the fields they might have accidentally insertet. Watch out in the process script missing array keys (numerical index from 0โ€“10 might be missing some values if the user deleted some form fields before submitting). You can reset the array keys with the array_merge function. Missing keys is an issue if you have two arrays you are trying to add into database as syncronized.
Updated to answer the comment.
Sorry, I don't undestand your question. You don't necessarily have to use hidden field. What you need is a database structure to match your forms function: to support one to many relationship. After all you are inserting multiple dates that relate to one person, or some specific event type, or what ever. Lets assume one user wants to add his three favorite dates in the world. Your form's source code looks like:
<input type="text" name='dateLover' id='dateLover'/>
<input type="text" name="dates[]" id="date1" /> //you need a increasing variable for these id numbers (or dont't put the id at all)
<input type="text" name="dates[]" id="date2" />
<input type="text" name="dates[]" id="date3" />
In addition you could have more fields such as <input type="text" name="extra" />. In submitted $_POST array there would be variables and arrays like: $_POST['dateLover'], $_POST['date'][0], $_POST['date'][1], $_POST['date'][2], $_POST['extra']. You'd take the non-repeatable values straight out of the $_POST array but you need a foreach (or some else loop) to handle the dates array.
Your database has to contain two tables (structure simplified):
person: id, dateLover
date: id, dateLover FK to person.dateLover, date
In your process script you have to:
insert a new dateLover to person and use last_insert_id to get his id
use a foreach to insert new dates to table date (with a dateLover's id as FK)
This all is pretty well demonstrated in the link I supplied earlier. For now, it's hard to give an complete example without undestanding the actual problem.
Update 2.
You are serializing the form, not the div's. So your (dynamically generated) could look like this:
<form id="form_educ" name="form_educ" method="post" action="form/educ.php">
<div id="educ">
<div><!--This is for layout only-->
<input type="text" name="dates[]" id="date0" />
<input type="text" name="names[]" id="name0" />
</div>
<div>
<input type="text" name="dates[]" id="date1" />
<input type="text" name="names[]" id="name1" />
</div>
<div>
<input type="text" name="dates[]" id="date2" />
<input type="text" name="names[]" id="name2" />
</div>
</div>
<input type="submit" name="form_educ" value="Refresh" />
</form>โ€‹
And in your process file you take these arrays from $_POST array and insert them into database maybe like this (with properly escaped and checked values of course...):
//dynamic part of the query
$qEnd = '';
$i = -1;
//this is static part of the query
$qBeginning = "INSERT INTO `date` (`id`, `date`, `name`) VALUES ";
foreach ($_POST['dates'] as $key => $date){
$i++;
$qValues[$i] = "(null, '{$date}', '{$_POST[names][$i]}')"; //never do this, always check values...
//value sets are concatenated one after another to the $qEnd
$qEnd .= $qValues . ',';
}
//combine the query parts and remove extra "," from the end
$q = $qBeginning . rtrim($qEnd, ',');
//now the (single) query ($q) is ready to be executed, echo it just for the fun of it
id should be auto increment field, or this kind of stuff doesn't work on the fly.
Again, this all should be clear in the jQuery link example so please read it carefully.
You should know all of the possible columns that could be updated before hand. Just check to see if those are set in the $_POST variable, then if they are append the insert or update statement with those values.
DANGER: Just looping on the $_POST variable looking at all params may end up inserting not database related POST fields into your insert statement and breaking.
Also when using these methods, be aware of SQL Injection, and use parameterized queries and never directly insert POST variable names or values into the SQL Statment.

MYSQL Update not updating database?

I have a simple Form along side a PHP update query that simply isn't working! I know the PHP is working on the page as there are several validation checks that need to be passed before hand which are working perfectly. The form its self is inside the Colorbox Popup tool.
My HTML Form Code is:
<div id="stylized" class="myform">
<form action="#" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>" />
<label>First Name:<span class="small">Enter your forename</span></label>
<input id="first_name" type="text" name="first_name" maxlength="50" placeholder="e.g. Joe" required autofocus/>
<div class="spacer"></div>
<input type="submit" id="update" name="update" value="Continue to Step 2!">
</form>
</div>
With the PHP Code as follows (this is above the HTML code on the page):
<?php
if($_POST['update']){
$user_i = $_POST['user_id'];
$f_name = $_POST['first_name'];
$first_name = ucfirst($f_name);
mysql_query("UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'") or die(mysql_error());
} ?>
The actual submit appears to be working, with the Popup refreshing afterwards, but the database does not update! I have triple checked the syntax and the database fields. 'user' and 'first_name' and 'user_id' is correct.
Update: Because the popup box refreshes, I cannot view the error's from the 'or die(mysql_error()) unfortunately, other wise i might have been one step closer.
Any help would be hugely appreciated.
Many thanks in advance.
When you say pop-up box, I assume you are using ajax to communicate from the form to the server, which as you stated is difficult to view submitted data. If this is the case try:
error_log(serialize($_POST));
This will force an entry in your error log with the $_POST data in serialized format, so you can check the values you are submitting are populated correctly.
You will also want to sanitize the variables you are adding to the SQL:
$sql = "UPDATE user SET first_name = " . mysql_real_escape_string($first_name) . " WHERE user_id = " . mysql_real_escape_string($user_i) . " LIMIT 1";
mysql_query($sql);
I would:
print_r($_POST); to view the POST data.
Generate the SQL from a string so it can be printed for debugging purposes, like so:
$sql = "UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'";
echo $sql;
mysql_query($sql) or die(mysql_error());
One of these techniques will likely tell you why the PHP-generated SQL doesn't update your database record.
you set your user_id field by echo $user_id; but your variable name is set to $user_i = $_POST['user_id'];
therefore your user id field is not set and your Mysql command will fail.

Problem with PHP & MySQL

I wrote this statements but it is not work :(
... can you tell me why?
HTML:
<form action="join.php" method="post">
<label name="RoomName">Room1</label>
</form>
PHP:
$roomName = $_POST['RoomName'];
$roomID = "SELECT RoomID FROM rooms WHERE RoomName = $roomName";
EDIT:
thanks but in my work the user does not have the ability to edit the room name
so i need to display the room name in a label (on any thing else) instead of text box
You need an <input> element as well.
<input type="text" name="RoomName">
This way the value is available by $_POST['RoomName']. You likely also need a submit button:
<input type="submit" value="Submit">
The label just associates the label with an input element, usually with the for attribute pointing to the input element's id:
<label for="RoomName">Room1</label>
<input type="text" id="RoomName" name="RoomName">
The benefit of this is mainly in accessibility (screen readers, clicking label, etc).
To learn more about HTML forms, go through this quick guide: http://www.w3schools.com/html/html_forms.asp
As to the SQL query, read the comments others posted to your question. You need to quote strings and escape the values from SQL injections as well.
Update: as per your edit, just set the readonly attribute to avoid the field being edited:
<input type="text" id="RoomName" name="RoomName" value="somevalue" readonly>
or make use of a hidden input element:
<input type="hidden" name="RoomName" value="somevalue">
Your code should look like this instead:
<form action="join.php" method="post">
<label name="RoomName">Room Name:</label>
<input type="text" name="RoomName" value="Room 1" />
<input type="submit" value="Submit Room" />
</form>
Also, you can't just set the value to the SQL query. You need to use the mysql_fetch_assoc() function. So it would be more like:
$sqlQuery = "SELECT RoomID FROM rooms WHERE RoomName = '".mysql_real_escape_string($roomName)."'";
$result = mysql_query($sqlQuery);
while ($row == mysql_fetch_assoc($result)) {
$roomID = $row['rooms'];
//do stuff with the current roomID
}
RoomName = $roomName"
to
RoomName = '$roomName'"
In SQL, strings must be quoted. Also, be safe by doing mysql_real_escape_string() on $roomName.

Categories