I have a form on a html page which allows me to select multiple items. The name of the form is name="region[]
It posts to another page where I use this code:
The region(s) selected:
<?php
$values = $_POST['region'];
foreach ($values as $region){
echo $region;
}
?>
This will display the results of the form perfectly; if there is one value it will print the one value, but if there is more than one then it will print them all.
I need to use the results of this in a query:
<?php
$con=mysqli_connect("****","****","****","****");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT
GoogleBusinessData.BusName,
GoogleBusinessData.BusAddress,
PostcodeTbl.PostcodeFirstTown,
PostcodeTbl.PostcodeFirstArea,
PostcodeTbl.Region,
PostcodeTbl.Postcode,
PostcodeTbl.PostcodeFirstLetters,
PostcodeTbl.PostcodeFirstPart,
PostcodeTbl.Country,
GoogleBusinessData.BusPhone,
GoogleBusinessData.BusCats,
GoogleBusinessData.FaroukCat,
GoogleBusinessData.BusWebsite,
GoogleBusinessData.BusDescription,
GoogleBusinessData.BusGoogleBusinessID,
GoogleBusinessData.BusPageURL,
EmailTable.EmailNumberOfEmails,
EmailTable.EmailAddresses
FROM
GoogleBusinessData
INNER JOIN PostcodeTbl ON GoogleBusinessData.BusPostalCode = PostcodeTbl.Postcode
INNER JOIN EmailTable ON GoogleBusinessData.BusWebsite = EmailTable.EmailWebsite
WHERE EmailTable.EmailNumberOfEmails > 0 AND
GoogleBusinessData.FaroukCat = 'Wedding Planner'
GROUP BY
GoogleBusinessData.BusWebsite
ORDER BY
GoogleBusinessData.BusName ASC
LIMIT 0,20");
while($row = mysqli_fetch_array($result))
{
echo $row['BusName'] . " - " . $row['PostcodeFirstTown'] . " - " . $row['PostcodeFirstArea'] . " - " . $row['Region'] . " - " . $row['Postcode'];
echo "<br>";
}
mysqli_close($con);
?>
So I need to add the condition in the WHERE to only return the results if it contains one of the regions with the form. I tried the following with no joy:
WHERE PostcodeTbl.Region IN ('$region') AND
EmailTable.EmailNumberOfEmails > 0 AND
GoogleBusinessData.FaroukCat = 'Wedding Planner'
But this only returns the last selection (as if there were only one selected).
Can anyone help?
In your first script, you are looping through the items. Each item is put into the variable $region one by one. So after the loop, $region contains the last item. If you construct the where clause at that time, it explains why the query only returns the last item.
To fix this, you'll have to construct a variable (e.g. $regions) that contains a list of regions.
For instance:
$regions = "'" . implode($_POST['region'], "','") . "'";
... WHERE PostcodeTbl.Region IN ('$regions') AND ...
Note that this is potentially unsafe, since the input in $_POST is not validated, so it is better to loop through the array (like you did) and validate each item one by one while constructing the string in $regions. You can use mysqli_real_escape_string for that.
Alternatively, and arguably better, is to use the parameter binding capabilities of mysqli. This is a bit tricky with array variables, but the details on how to do that are already described in this question.
Related
I have Two Tables userwhich has field userName and another table page which has field pageUserName so im selecting this two tables form the database in while loop but i want to echo this two Names in same while loop one after another like we have in FB their are userName as Well as Page names in news feed how can i do this ????
<?php
$sql=mysql_query("SELECT * FROM user LEFT JOIN page ON user.userID=page.userID") ;
while($row=mysql_fetch_assoc());
{
//For First Loop It Should Be UserName
echo $row['userName'];
//For 2nd Loop It Should Be pageUserName
echo $row['pageUserName'];
} ?>
This is the code but the echo gets print together i want separate echo for userName and another for pageUserName one after another and not together
You mean this?
<?php
$sql=mysql_query("SELECT * FROM user LEFT JOIN page ON user.userID=page.userID") ;
while($row=mysql_fetch_assoc())
{
echo $row['userName'] . ' ' . $row['pageUserName'];
}
?>
inside loop make a single line as follows:
<?php echo $row['userName']. " - ". $row['pageUserName']."<br>" ?>
<?php
$sql=mysql_query("SELECT * FROM user LEFT JOIN page ON user.userID=page.userID") ;
while($row=mysql_fetch_assoc());
{
echo $row['userName']." ".$row['pageUserName']."<br />";
}
?>
Try like this:
<?php
$sql = mysql_query("SELECT * FROM user LEFT JOIN page ON user.userID=page.userID");
while ($row = mysql_fetch_assoc()) {
echo $row['userName'] . " " . $row['pageUserName'] . "<br>";
}
?>
NOTE
You should not use open / end php tag in each row.
You can concatenate your string with . character as in my example.
WARNING
mysql_* functions are deprecated, use mysqli_* or PDO instead.
UPDATE
Based on OP edit in his original question, I think I get it what he wants. When you iterate through your results, instead echo put them into 2 arrays.
Then iterate through both of them. I write for this a little function called showNames, so you avoid code repetation.
function showNames($array) {
foreach ($array as $item) {
echo $item."<br>";
}
}
//Init arrays
$userNames = [];
$pageUserNames = [];
while ($row = mysql_fetch_assoc()) {
//Put values into the 2 arrays
$userNames[] = $row['userName'];
$pageUserNames[] = $row['pageUserName'];
}
//Show the items of arrays
showNames($userNames);
echo '<hr>';
showNames($pageUserNames);
I'm cobbling together a dropdown list that I would like to display the '[ve_venue]", "[ve_town]' from a MySQL query and, upon selection set a variable that I can use to pass the ve_ID on to an update query that adds a venue ID number to a separate table as a lookup key.
So far I've got some code that I've pieced together from various places and I can get it to display the town in a dropdown - I just need to add the venue field to the dropdown so I get "venue, town" in the list and I also need to be able to pass the ve_ID to a variable, say, $ve_ID so I can call it in some separate code (that will be on the same page in a separate include).
Here's what I've got so far....
<?
include('login_admin_sucess.php');
// Connects to your Database
include '../connect_include.php';
$query = "SELECT ve_ID, ve_venue, ve_town FROM `co_venues` ORDER BY ve_ID ";
$result = mysql_query($query);
while($r=mysql_fetch_array($result))
{
$ve_venue = $r['ve_venue'];
$result_array[$ve_venue][] = $r['ve_town'];
}
echo "<select name='x'>";
foreach($result_array as $v_venue => $value)
{
foreach($value as $title) {
echo "<option value='" . $v_venue . "'>" . $title . "</option>";
}
}
echo "</select>";
?>
I realise that mysql_ is deprecated...I'll work on that once I've got everything functioning.
You can concat the id and venue. For example:
$ve_venue = $r['ve_venue'] . "|" . $r['ve_ID'];
When you use the variable make a split with charapter "|" with preg_split function.
I'm trying to create a simple e-commerce system. First thing I did was select the rows with the same Order ID from mysql. My table looks like this:
Now, I'd like to know how I can group them into separate divs, it should look like this:
Here's my code:
$con = mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result2 = mysqli_query($con, "SELECT DISTINCT request_date, department_id FROM tbl_requests WHERE request_id=".$_GET['request_id']) ;
while($row2 = mysqli_fetch_array($result2)) {
echo "" . $row2['request_date'] . "<br/>";
echo "Order from Department " . $row2['department_id'] . "<br/>";
echo "<br/>";
echo "<hr/>";
echo "<br/>";
}
$result = mysqli_query($con,"SELECT * FROM tbl_requests WHERE request_id=".$_GET['request_id']);
while($row = mysqli_fetch_array($result)) {
echo "" . $row['request_details'] . "";
echo "<br/>";
}
I'm sorry if ever this question is incomplete, please feel free to ask me any more questions. Thank you in advance :)
You can check for every product in array using Javascript or jQuery(much easier).
This way you can check if your page does contain any existing div with that manufacture id (ie. #m_1055, #m_1040) or not.
If div does exist, append product in that div (in jQuery.append())
If not, then first append the div with that manufacture id to the document and then append the product to it.
I am attempting to use two queries to set up multiple dropdown menus per doctor. So far this is working, however it unfortunately pulls only the item.
I would like to have all of the 'expertises' available within the dropdown (and the expertise IDs as the option values).
I have set up the below while loop, however I have been unsuccessful in producing a dropdown for each Client_ID.
The first query (below) pulls the client ID from the area
$client_id = $_GET['doc_id'];
$physician_id_expertise = $client_id;
$doctor_query = 'SELECT * ';
$doctor_query.= 'FROM `primarycare_expertise` ';
$doctor_query.= 'WHERE `physician_id`=' . $client_id . ' ';
$doctor_result = mysql_unbuffered_query( $doctor_query );
The while loop incorporates the second query, which sets up the dropdown (pulling in all of the 'expertise' values).
while ($doctor_row = mysql_fetch_array( $doctor_result ))
{
echo "<select name='doc_id_expertise_" . $doctor_row['pe_id'] . "' id='doc_id_expertise_" . $doctor_row['pe_id'] . "'>";
$expert_query = 'SELECT * FROM `expertise` ';
$expert_result = mysql_unbuffered_query( $expert_query );
while ($expert_row = mysql_fetch_array( $expert_result )){
if($doctor_row['expertise_id'] == $expert_row['expertise_id'])
{
$selected = "selected";
} else {
$selected = "";
}
echo "<option $selected value=" . $expert_row['expertise_id'] . ">" . $expert_row['expertise'] . "</option>";
}
echo "</select>";
echo "<br />";
}
If any of you could help me out, I would be very appreciative! Thank you for your time!
You are sending new query while iterating through unbuffered result of previous query. This does not work. Try using mysql_query instead of mysql_unbuffered_query for the first query like this:
$doctor_result = mysql_query (
"SELECT * FROM primarycare_expertise WHERE physician_id='$client_id'");
For subsequent queries you could still use mysql_unbuffered_query because they do not overlap.
See the following page for details.
The mysql package is deprecated BTW. Consider adopting to the mysqli extension instead.
http://www.php.net/manual/en/book.mysqli.php
After using the search criteria for my database search, I do get the desired records, but I dont want to display all the fields(85 fields) for each of the records; instead I've displayed only 5 of them, and then wish to give a hyperlink saying "Click for further Details", so that the users can then go ahead and view all the fields for a particular record.
For eg, if the user enters "abc" in Search box, and the database contains 5 records with "abc", then it'll show all 5 records, but only 5 specific fields. But to view all the fields, for say the 1st "abc" record, the user will click on "further details", which will direct him to another page with all the 85 fields for that particular 1st abc record.
Kindly guide me through! I dont know what conditions to give, because i tried doing it with header(Location), but displays all the records, and doesn't even take that particular processed sql query!
Here's an example of what you could do. It's a self-referencing search page that first uses a generic query to get all records. Then, as it cycles through each record (only grabbing specific fields, it makes a form that uses a hidden variable with the Primary Key/Unique ID to send to itself (search.php) as a POST variable. Then, when that POST variable is detected, the query only grabs that 1 specific record and using an IF/THEN statement in the WHILE loop, shows all 80+ fields.
There are better ways to do querying and handling form data, but this should get you started. Please select this as an answer if it works.
search.php
<?php
$query = "SELECT * FROM table";
if (!empty($_POST['id'])) {
$query = "SELECT * FROM table WHERE id_field = '" . $_POST['id'] . "'";
}
$query_info = mysql_query($query) or die(mysql_error());
$query_info_count = mysql_num_rows($query_info);
while($query_info_details = mysql_fetch_array($query_info)){
if ($query_info_count > 1) {
$field_a = $query_info_details['field_a'];
$field_d = $query_info_details['field_d']; // Say this is the Primary Key
$field_f = $query_info_details['field_f'];
$field_g = $query_info_details['field_g'];
$field_s = $query_info_details['field_s'];
echo "<form method='post' action='search.php'>";
echo "Name: " . $field_a . " - " . $field_f . " - ID: " . $field_d;
echo " - Location: " . $field_g . "(" . $field_s . ")";
echo "<input type='hidden' name='id' value='" . $field_d . "'>
<input type='submit' value='View This Record'><br><br>";
}
else {
// Display all fields for record using $query_info_details['field_X'] from above
}
}
?>
$where_str="";
if(isset($_POST['searchBox']))
{
$searchStr=$_POST['searchText'];
$where_str="colx =". $searchStr ;
}
$standard_query ="select col1, col2,col3,col4,col5 from tableName ". $where_str;
Then in display
while($row=mysql_fetch_array($records))
{
echo"<a href='' onclick='openDetail(\"$row[index]\")'>$row[index] </a>";
...
}
Javascript
function openDetail(index)
{
window.open("Detail.php?rowindex"+ index);
return false;
}
// Detail.php
if(isset($_GET['rowindex'])
{
$row_index=$_GET['rowindex'];
$detail_query="select * from tableName where index=$row_index";
...
}