How to use a selection to generate an sql query - php

I need to use the selection from and HTML select element as one of the variables in my sql query. Meaning if the user selects "Iphone" from the list, I want to query to be something like select * where name = Iphone.
I do not know how to go about this, thank you.
This code creates the select based on the query:
<option disabled selected value> -- Select a forum -- </option>
<?php
$con = mysqli_connect("host","user","pass","db");
if (!$con) {
die('Connection failed: ' . mysqli_connect_error() . '<br>');
}
$productName='SELECT p.name
FROM product as p
JOIN ownedproducts as o on o.productID = p.productID
WHERE usersID =2;';
$result=mysqli_query($con, $productName);
while ($row = mysqli_fetch_assoc($result)) {
unset($id);
$id = $row['name'];
echo '<option value="'.$id.'">'.$id.'</option>';
}
</select>
I would like to take what the user selects, including multiple selections, and build a table based on that something like this where the AND p.name = selected is replaced with what would actually work in this case. I think javascript is the way to go but I do not know enough.
<?php
$query1 = $db->query('SELECT p.productID, p.name, p.company, o.prodtype AS Type
FROM ownedproducts AS o
JOIN product as p ON p.productID = o.productID
WHERE o.usersID = 2
AND p.name = selected');
while ($row = $query1->fetch())
{
if . $row['name'] . = selected:
echo "<tr id=" . $row['productID'] . ">";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['Type'] . "</td>";
echo "</tr>";
}
?>
Edited for more detail.
Thanks in advance

Though, I am not sure what are you asking for but select statement for exact match will be like below=>
select * from tablename where name='Iphone';
or if you want partial match then you can use wildcard(%) and like operator given below =>
select * from tablename where name like '%Iphone%';

Related

getting a result of a table Mysqli left join

So what i want is the following. I have 3 tables: first i will explain in english what i want for final result:
let me explain all in english:
table 1 is REGISTERED_MEMBERS
table 2 is OPEN CLASSES
table 3 i want who appplied and to which class they applied and show that in a table when date is selected from a dropdown list!
This is how it should show at the end:
table = razpisani_tecaji with (ID_TECAJA, DATE, STATUS, ST_ODPRTIH_MEST)
table = registrirani_clani wtih (ID_TECAJNIKA,IME,PRIIMEK, EMAIL)
table = prijave_na_tecaj with (ID_TECAJNIKA, ID_TECAJA, PLACILO)
now in HTML i have a dropdown list populated with dates (this works ok) from table 1.
<form>
<select name="dates" onchange="showUser(this.value)">
<option value="" selected="selected">Izberi datum za pregled</option>;
<?php
$con = mysqli_connect('localhost','root','','viverius_education');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = mysqli_query($con, "SELECT ID_TECAJA, DATUM FROM razpisani_tecaji");
while ($row = $sql->fetch_assoc()){
echo "<option value='" . $row['ID_TECAJA'] . "'>" . $row['DATUM'] . "</option>";
}
?>
Here a ID is saved to a variable q which is then send to php via JS. This all works. Now what i would like is for user to select a date and get a results from 3. table only to show IME from linked to ID_TECAJNIKA and PLACILO linked to ID_TECAJNIKA.
THis is what i have in PHP so far:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','viverius_education');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT razpisani_tecaji.ID_TECAJA, registrirani_clani._ID_TECAJNIKA FROM prijave_na_tecaj
LEFT JOIN razpisani_tecaji ON prijave_na_tecaj.ID_TECAJA = razpisani_tecaji.ID_TECAJA
LEFT JOIN registrirani_clani ON prijave_na_tecaj.ID_TECAJNIKA = registrirani_clani.ID_TECAJNIKA";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Ime</th>
<th>Placilo</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['ID_TECAJNIKA'] . "</td>";
echo "<td>" . $row['PLACILO'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
$sql="select registrirani_clani., prijave_na_tecaj.,razpisani_tecaji.*
from registrirani_clani
left join prijave_na_tecaj on registrirani_clani.ID_TECAJNIKA = prijave_na_tecaj.ID_TECAJNIKA
left join razpisani_tecaji ON razpisani_tecaji.ID_TECAJA = prijave_na_tecaj.ID_TECAJA
where razpisani_tecaji.ID_TECAJA = '".$q."'";

Search running spatially with PHP, MYSQL, GROUP_CONCAT and JOIN

I made some changes in the code and now it's working. But there is a new problem.
In the database, I have registered 3 Company Cods: G-1001, G-1002 and G-1004.
If I type "g", "g-", or for instance "g-100" and click search, it returns me all the results correctly. But if I type just "g-1001" or even "01", "001", it returns no results.
Why it's not working when I search the last characters of the registered code?
<?php
if(isset($_POST['action']) && $_POST['action'] == 'send'){
$codsearch = preg_replace('#[^a-z 0-9?()!-]#i', '', $_POST['searchcompanycod']);
$getresultsquery = mysql_query('SELECT p.*, a.idProduct, a.idVehic, a.year, v.nameVehic, GROUP_CONCAT(a.year SEPARATOR "<br>"), GROUP_CONCAT(a.idVehic SEPARATOR "<br>"), GROUP_CONCAT(v.nameVehic SEPARATOR "<br>")
FROM products p
INNER JOIN application a ON p.idProduct = a.idProduct
INNER JOIN vehic v ON a.idVehic = v.idVehic
WHERE codCompany LIKE "%'.$codsearch.'%"
GROUP BY p.codCompany') or die(mysql_error());
$resultsrow = mysql_num_rows($getresultsquery);
if($resultsrow > 1){
echo "$codsearch";
echo "<table class='table table-bordered' border=1>";
echo "<tr>";
echo "<th>Company Code</th><th>Original Code</th><th>Descr.</th><th>idProduct</th><th>idVehic</th><th>Vehic Name</th><th>Year</th>";
echo "</tr>";
while($getresultsline = mysql_fetch_array($getresultsquery)) {
echo "<tr>";
echo "<td>" . $getresultsline['codCompany'] . "</td>";
echo "<td>" . $getresultsline['codOriginal'] . "</td>";
echo "<td>" . $getresultsline['typeDesc'] . "</td>";
echo "<td>" . $getresultsline['idProduct'] . "</td>";
echo "<td>" . $getresultsline['GROUP_CONCAT(a.idVehic SEPARATOR "<br>")'] . "</td>";
echo "<td>" . $getresultsline['GROUP_CONCAT(v.nameVehic SEPARATOR "<br>")'] . "</td>";
echo "<td>" . $getresultsline['GROUP_CONCAT(a.year SEPARATOR "<br>")'] . "</td>";
echo "</tr>";
}
} else{
echo "No results";}
}
?>
</tbody>
</table>
Any ideas?
My testing page is: http://flyingmail.com.br/test/produtos.php (only Company Code filter working)
The highlighting on your SQL should show you the main issue.
Change
'SELECT table1.*, table2.productID, table2.veicleID, table2.date, table3.veicleNAME, GROUP_CONCAT(table2.date SEPARATOR "<br>"), GROUP_CONCAT(table3.veicleNAME SEPARATOR "<br>")
FROM table1
INNER JOIN table2 ON table1.productID = table2.productID
INNER JOIN table3 ON table2.veicleID = table3.veicleID
GROUP BY productID
HAVING productID LIKE '%".$codsearch."%''
to
"SELECT table1.*, table2.productID, table2.veicleID, table2.date, table3.veicleNAME, GROUP_CONCAT(table2.date SEPARATOR "<br>"), GROUP_CONCAT(table3.veicleNAME SEPARATOR "<br>")
FROM table1
INNER JOIN table2 ON table1.productID = table2.productID
INNER JOIN table3 ON table2.veicleID = table3.veicleID
GROUP BY productID
HAVING productID LIKE '%".$codsearch."%'"
(note that I changed the first and last single quote to a double quote)
Found it. Hahaha terrible... it could never be if($resultsrow > 1){ because if I search for something specific, it will return only 1 row. So, it must be if($resultsrow >= 1){
LOL

Select from dropdown -> compare -> if match -> show picture

Good day all,
I've got a code that reads the users from a database and puts them in a dropdown menu:
<?php
mysql_connect('', '', '');
mysql_select_db ("");
$sql = "SELECT id,name FROM jos_users";
$result = mysql_query($sql);
echo "<select name='deelnemers' onchange='copyId2textinput(this);'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
Now i've got another database called jos_comprofiler with also an ID and also a avatar (image).
I was wondering if somebody give me some advise to compare the ID's from the 2 tables and then show the picture.
So for example, if i click on a user in the dropdown, it must look if there's a ID match with the other table, and if there is, show the picture from 'avatar'.
Thank you for your help and excuse me for my bad english!
Query can be:
SELECT `ju`.`id`, `ju`.`name`, `jcp`.`avatar` FROM `jos_users` as `ju`
LEFT JOIN `jos_comprofiler` as `jcp` ON (`ju`.`id` = `jcp`.`id`)
Here we use a left join, which means the jos_comprofiler does not need to exist for every jos_users. In those cases the field 'avatar' will be NULL.
Then you have in row the element 'avatar' which can be either NULL or a value.
if($row['avatar'] != NULL) echo "<img src=\"".$row['avatar']."\">";
or something :) good luck
There would be some ways but I'll show fast one.
<?php
mysql_connect('', '', '');
mysql_select_db ("");
$sql = "SELECT u.id, name, avatar FROM jos_users AS u LEFT JOIN jos_comprofiler USING(id)";
$result = mysql_query($sql);
echo "<div id='imgContainer'></div>";
echo "<select name='deelnemers' onchange='showAvatar(this.value);'>";
$avatars = array();
while ($row = mysql_fetch_array($result)) {
if($row['avatar']){
$avatars[$row['id']] = $row['avatar'];
}
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<script>
var avatars = <?=json_encode($avatars)?>;
//alert(avatars[5]);
var avatarContainer = document.getElementById('imgContainer');
function showAvatar(id) {
if(avatars[id]===undefined) return false;
avatarContainer.innerHTML = '<img src="/path/'+avatars[id]+'" />';
}
</script>
This should work, with some modification for your code: img path, etc..

How to get the value from the primary key AND foreign key when joining mySQL tables?

I have two tables, employee as the parent and license as the child. They both have a Lic_ID column for reference, this column is the PK in license and the FK in employee. The license table also has a column Lic_Type which holds the name of the license.
I am trying to create a table with list boxes so the employee table can be updated. The list box value needs to be populated with the license.Lic_ID and the license.Lic_Type is to be displayed in the option. Here is what I have:
(Employee name, Id, etc. called out up here)
<?php
echo "<select name=\"Lic\">";
echo "<option value=\"\">Select...</option>";
$sql = $mysqli->query("SELECT Lic_ID, Lic_Type FROM license");
while($row = $result->fetch_assoc())
{
echo "<option value=\"" . $row['Lic_ID'] . "\">" . $row['Lic_Type'] . "</option>";
}
echo "</select>";
?>
So that works good, it shows the license type and has the value set to the license id. What I want to do is have <option selected="selected"> if the license id is set for an employee. This code doesn't work, but I think it illustrates what I'm trying to do:
<?php
echo "<select name=\"Lic\">";
echo "<option value=\"\">Select...</option>";
$sql = $mysqli->query("SELECT license.Lic_ID, license.Lic_Type, employee.Lic_ID FROM employee INNER JOIN license ON employee.Lic_ID = license.Lic_ID");
while($row = $result->fetch_assoc())
{
echo "<option value=\"" . $row['license.Lic_ID'] . "\"";
if($row['employee.Lic_ID'] = $row['license.Lic_ID']){echo "selected=\"selected\";}
echo ">" . $row['license.Lic_Type'] . "</option>";
}
echo "</select>";
?>
Is there a way to accomplish what I'm trying to do?
I think there may have been some confusion on what exactly I was trying to accomplish, I apologize for not being very clear. Anyways, I stumbled over the answer today, so I thought I should post it.
$sql1 = ("SELECT Emp_Name, Lic_MAT_ID FROM employee");
if(!$result_employee_query = $mysqli->query($sql1))
{
die ("There was an error getting the records from the employee table");
}
while($employee = $result_employee_query->fetch_assoc())
{
echo "Employee Name: " . $employee['Emp_Name'] . "<br>";
echo "License: ";
echo "<select>";
$sql2 = ("SELECT Lic_MAT_ID, Lic_MAT_Type FROM license_mat");
if(!$result_license_query = $mysqli->query($sql2))
{
die ("There was an error getting the records from the license table");
}
while($license = $result_license_query->fetch_assoc())
{
echo "<option value=\"" . $license ['Lic_MAT_ID'] . "\"";
if($license['Lic_MAT_ID'] == $employee['Lic_MAT_ID'])
{
echo " selected=\"selected\"";
}
echo ">" . $license ['Lic_MAT_Type'] . "</option>";
}
echo "</select><br>";
}
As I understand your problem: You want to see if the License has been added to ANY users or has it been unassigned. If any of the users have the license set then it's "selected", othervize not.
First you have to assign the keyword "multiple" to your select object to make it a listbox:
echo "<select name=\"Lic\" multiple=\"multiple\">";
Second: I would write this kind of query:
$sql = $mysqli->query("SELECT l.Lic_ID, l.Lic_Type, e.cnt FROM licence l left outer join (select Lic_id, count(*) cnt from employee group by Lic_id) e on l.Lic_ID=e.Lic_id");
It selects the Lic_ID, Lic_Type and the count of how many employees have the respective Lic_ID set to it (left outer join)
and in the code just check, if the count is higher then 0
if($row['cnt'] > 0){
echo "selected=\"selected\";
}

PHP and Multiple DB Selects

I've got two tables from which I need to extract information, but the data from the second table depends on the information I get from the first one. Is there an easy way to handle this?
<?php
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('stadium') or die(mysql_error());
$result = mysql_query("SELECT * FROM events");
$result2 = mysql_query("SELECT name FROM competitions WHERE id='$row[competition_id]' ");
while($row = mysql_fetch_array($result)) {
echo "<tr id=\"" . $row['id'] . "\"> \n<td>" . $row['name'] . "</td>";
echo "<td>" . $row['competition_id'] . "</td>";
echo "<td>" . $row['date'] . "</td></tr>";
}
?>
Use a JOIN.
SELECT e.*, c.name as competition_name FROM events e LEFT JOIN competitions c on c.id = e.competition_id

Categories