Search running spatially with PHP, MYSQL, GROUP_CONCAT and JOIN - php

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

Related

How to use a selection to generate an sql query

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%';

How do i loop through but replace missing data with blanks in table

I am trying to display a table to show all the subjects the first student takes, then all the progress grades the student has made in that subject.
However, a student may not have a grade in a certain column so i need to place a blank or 'no grade' in place of it.
Instead i get them stacked side by side...
As you can see below '7(Pc3)' in English should be in the 'PC3' column and 'PC2' should say no grade or blank.... If possible -
Thanks
I have the loop working to fetch the students, plus the loop working to fetch all the subjects for that student.
And can display all the grades - but they don't line up with the right column
while ($res = $result->fetch_assoc()) {
echo "<tr><td>" . $res['subname'] . "</td>";
$result2 = mysqli_query($mysqli, "SELECT *
FROM grades
JOIN gradesets ON grades.gradeset_id = gradesets.id
WHERE grades.student_id = {$row['id']}
AND grades.subject_id = {$res['id']}
ORDER BY grades.gradeset_id ") or die($mysqli->error);
while ($res2 = $result2->fetch_assoc()) {
echo "<td>" . $res2['grade'] . "</td>";
//echo "<td>" . $res2['gradeset_id'] . "</td>";
//print_r($res2);
$resset = $res2['gradeset'];
$resset2 = substr($resset, -1);
//print_r($resset);
//print_r($resset2);
}
}
So i can echo out the right grades, but need to test they match up in the right columns... Here is the full code if needed...
$student = $mysqli->query("SELECT * FROM student");
echo "<center>";
echo "<h2>Data Wall</h2>";
echo "<h3>PHP</h3>";
echo "<hr/>";
while ($row = $student->fetch_assoc()) {
echo "<table border='1'>
<tr>
<th>ID</th>
<th>STUDENT</th>
<th>HOUSE</th>
</tr><br>";
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['stuname'] . "</td>";
echo "<td>" . $row['house'] . "</td>";
echo "</tr><br><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>";
echo "<tr><th>SUBJECTS</th><th>PC1</th><th>PC2</th><th>PC3</th><th>PC4</th></tr>";
$result = mysqli_query($mysqli, "SELECT subjects.id,subjects.subname
FROM student
JOIN grades ON student.id = grades.student_id
JOIN subjects ON subjects.id = grades.subject_id
WHERE student.id = {$row['id']}
GROUP BY subjects.subname ORDER BY subjects.id ") or die($mysqli->error);
while ($res = $result->fetch_assoc()) {
echo "<tr><td>" . $res['subname'] . "</td>";
$result2 = mysqli_query($mysqli, "SELECT *
FROM grades
JOIN gradesets ON grades.gradeset_id = gradesets.id
WHERE grades.student_id = {$row['id']}
AND grades.subject_id = {$res['id']}
ORDER BY grades.gradeset_id ") or die($mysqli->error);
while ($res2 = $result2->fetch_assoc()) {
echo "<td>" . $res2['grade'] . "</td>";
//echo "<td>" . $res2['gradeset_id'] . "</td>";
//print_r($res2);
$resset = $res2['gradeset'];
$resset2 = substr($resset, -1);
//print_r($resset);
//print_r($resset2);
}
}
}
echo "</tr>";
echo "</table>";
echo "</center>";
$mysqli->close();
?>
Since PHP 5.3 you can use Elvis operator - ?:
And since PHP 7 you are able to use Null Coalescing Operator - ??
Either of these you can use to display some other information if you row is empty. For example (PHP 7+):
echo "<td>" . ($res2['grade'] ?? 'No grade') . "</td>";
Would result to either a grade, or No grade text if string is empty or false.
Hope this helps!
In your inner query, you're doing an INNER JOIN, which selects only those rows that have a match in the gradeset table. It looks like you want a LEFT OUTER JOIN, so that you get null placeholders where there is no match:
SELECT *
FROM grades
LEFT JOIN gradesets ON grades.gradeset_id = gradesets.id
WHERE grades.student_id = {$row['id']}
AND grades.subject_id = {$res['id']}
ORDER BY grades.gradeset_id
This way, in your query result, instead of getting:
4 (PC1)
7 (PC3)
6 (PC4)
You'll get:
4 (PC1)
null
7 (PC3)
6 (PC4)
You could build an array of empty grades and then replace them with any data from the query. Like so:
$grades = [1 => '', 2 => '', 3 => '', 4 => ''];
while ($res2 = $result2->fetch_assoc()) {
$grades[$res2['gradeset']] = $res2['grade'];
}
foreach ($grades as $grade) {
echo "<td>" . $grade . "</td>";
}

php mysql select from columns from 2 tables Join

I have two tables.
visitors_details, with id,scanner_id,time columns
and visitors_info with scanner_id, name,surname columns
I want to get back
id,name,surname,time in a table
i have written this but is not working
$result = mysql_query("SELECT visitors_details.id AS id,
visitors_info.name AS name, visitors_info.surname AS surname, visitors_details.time
AS time FROM visitors_details AS d LEFT JOIN visitors_info AS i ON
d.scanner_id=i.scanner_id ");
echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>surname</th>
<th>Time</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['time'] . "</td>";
echo "</tr>";
}
echo "</table>";
any ideas??
Its better to enable some debugging for your code like this:
<?php
error_reporting(E_ALL);
$sql = "
SELECT d.id AS id, i.name AS name, i.surname AS surname, d.time AS time
FROM visitors_details AS d
LEFT JOIN visitors_info AS i ON d.scanner_id=i.scanner_id
";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
try this query
$result = mysql_query("SELECT d.id , i.name , i.surname , d.time
FROM visitors_details AS d LEFT JOIN visitors_info AS i
ON d.scanner_id=i.scanner_id ");
Add this to catch errors. saves a lot of time:
if(!$result) {
echo mysql_error();
}

Convert MYSQL query to PHP Query

I have been trying to get this to work for some time. I'm just stumped. Here is the original MYSQL and then the PHP Ive been working on.
MYSQL:
SET #COD_PAIS = 3;
SET #F_HASTACORTE = '2012-03-31 01:00:00';
SELECT mcarteras.DES_CARTERA_CC AS 'Short Name of Fund'
, mcarterasflias.DES_CARTERAFLIA AS 'I/C'
, msociedades.DES_SOCIEDAD_CORTO AS 'Fund Manager Company'
, mcarteras_clases.DES_CARTERACLASE AS 'Class'
, mcarteras_clasesesp.DES_CARTERACLASE_ESP AS 'Special Class'
, dr_rentmovil_carteras.POR_RENTCARTERA AS 'TTR year-to-date %'
, dficha_mes.POR_REMUNERA_COBRADA AS 'Mgmt Fee Effectively Charged'
, dficha_mes.POR_GASTOS_TOTALESC AS 'Total Expenses %'
, dficha_mes.VR_CARTERA_FCORTE AS 'Fund Size'
, dr_rentmovil_carteras.F_HASTACORTE AS 'Date'
FROM mcarteras
INNER
JOIN mcarterasflias
ON mcarterasflias.ID_CARTERAFLIA = mcarteras.ID_CARTERAFLIA
INNER
JOIN msociedades
ON msociedades.ID_SOCIEDAD = mcarteras.ID_SOCIEDADADM
INNER
JOIN mcarteras_clases
ON mcarteras_clases.ID_CARTERACLASE = mcarteras.ID_CARTERACLASE
INNER
JOIN mcarteras_clasesesp
ON mcarteras_clasesesp.ID_CARTERACLASE_ESP = mcarteras.ID_CARTERACLASE_ESP
INNER
JOIN dr_rentmovil_carteras
ON dr_rentmovil_carteras.ID_CARTERA = mcarteras.ID_CARTERA
AND dr_rentmovil_carteras.COD_PAIS = #COD_PAIS
AND dr_rentmovil_carteras.F_HASTACORTE =#F_HASTACORTE
AND dr_rentmovil_carteras.ID_FORMATO = 1
AND dr_rentmovil_carteras. ID_COLUMNA = 5
INNER
JOIN dficha_mes
ON dficha_mes.ID_CARTERA = mcarteras.ID_CARTERA
AND dficha_mes.COD_PAIS = #COD_PAIS
AND dficha_mes.F_CORTE = #F_HASTACORTE
WHERE mcarteras.COD_PAIS = #COD_PAIS
AND mcarteras.ID_CARTERATIPO = 4
AND mcarteras.ID_CARTERAFLIA IN ( 3,4 )
AND mcarteras.IND_PUBLICACION = 1
AND mcarteras.COD_ESTADO= 1
PHP:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bdcarterascv2", $con);
$COD_PAIS = '3';
$F_HASTACORTE = '2012-03-31 01:00:00';
$result = mysql_query("SELECT DES_CARTERA_CC AS 'Short Name of Fund'
, mcarterasflias.DES_CARTERAFLIA AS 'I/C'
, msociedades.DES_SOCIEDAD_CORTO AS 'Fund Manager Company'
, mcarteras_clases.DES_CARTERACLASE AS 'Class'
, mcarteras_clasesesp.DES_CARTERACLASE_ESP AS 'Special Class'
, dr_rentmovil_carteras.POR_RENTCARTERA AS 'TTR year-to-date %'
, dficha_mes.POR_REMUNERA_COBRADA AS 'Mgmt Fee Effectively Charged'
, dficha_mes.POR_GASTOS_TOTALESC AS 'Total Expenses %'
, dficha_mes.VR_CARTERA_FCORTE AS 'Fund Size'
,dr_rentmovil_carteras.F_HASTACORTE AS'Date'
FROM mcarteras
INNER
JOIN mcarterasflias
ON mcarterasflias.ID_CARTERAFLIA = mcarteras.ID_CARTERAFLIA
INNER
JOIN msociedades
ON msociedades.ID_SOCIEDAD = mcarteras.ID_SOCIEDADADM
INNER
JOIN mcarteras_clases
ON mcarteras_clases.ID_CARTERACLASE = mcarteras.ID_CARTERACLASE
INNER
JOIN mcarteras_clasesesp
ON mcarteras_clasesesp.ID_CARTERACLASE_ESP = mcarteras.ID_CARTERACLASE_ESP
INNER
JOIN dr_rentmovil_carteras
ON dr_rentmovil_carteras.ID_CARTERA = mcarteras.ID_CARTERA
AND dr_rentmovil_carteras.COD_PAIS = $COD_PAIS
AND dr_rentmovil_carteras.F_HASTACORTE = $F_HASTACORTE
AND dr_rentmovil_carteras.ID_FORMATO = 1
AND dr_rentmovil_carteras. ID_COLUMNA = 5
INNER
JOIN dficha_mes
ON dficha_mes.ID_CARTERA = mcarteras.ID_CARTERA
AND dficha_mes.COD_PAIS = $COD_PAIS
AND dficha_mes.F_CORTE = $F_HASTACORTE
WHERE mcarteras.COD_PAIS = $COD_PAIS
AND mcarteras.ID_CARTERATIPO = 4
AND mcarteras.ID_CARTERAFLIA IN ( 3,4 )
AND mcarteras.IND_PUBLICACION = 1
AND mcarteras.COD_ESTADO= 1
")
or die(mysql_error());
// HTML ... Aliases from Mysql
echo "<table border='1'>
<tr>
<th>Short Name of Fund</th>
<th>I/C</th>
<th>Fund Manager Company</th>
<th>Class</th>
<th>Special Class</th>
<th>TTR year-to-date %</th>
<th>Mgmt Fee Effectively Charged</th>
<th>Total Expenses %</th>
<th>Fund Size</th>
<th>Date</th>
</tr>";
//<tr> specifies table row. for each <td> (table data) will specify a new column. The $row specifies the mysql column name (in this case using an alias)
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Short Name of Fund'] . "</td>";
echo "<td>" . $row['I/C'] . "</td>";
echo "<td>" . $row['Fund Manager Company'] . "</td>";
echo "<td>" . $row['Class'] . "</td>";
echo "<td>" . $row['Special Class'] . "</td>";
echo "<td>" . $row['TTR year-to-date %'] . "</td>";
echo "<td>" . $row['Mgmt Fee Effectively Charged'] . "</td>";
echo "<td>" . $row['Total Expenses %'] . "</td>";
echo "<td>" . $row['Fund Size'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Here is the current error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '01:00:00 AND dr_rentmovil_carteras.ID_FORMATO = 1 AND dr_rentmovil_carte' at line 28
Any help would be greatly appreciated.
You need to wrap the datetime string in quotes:
='$F_HASTACORTE'
Otherwise it is evaluating 2012-03-31 01:00:00 as a number, not a datetime.
you probably want to put quotes around your '$VARIABLES'. And escape them if you didn't.
Try:
AND dr_rentmovil_carteras.F_HASTACORTE = '$F_HASTACORTE'
If your variables aren't integers, you should quote them - there are a few other places where you should do that, too.
You should also look at using PDO instead of the mysql_* functions, too - if you use bound parameters, you can sidestep a lot of this sort of problem very neatly.

how do you join two tables

i have a mysql query which is trying to join to tables to show the data from two tables onto one table on the webpage?
<?php
include 'library/connect.php';
$result = mysql_query("SELECT * FROM meetings INNER JOIN rooms USING ('room', 'date', 'time' ) ");
echo "<table border='1'><tr><th>Title</th><th>Chairman</th><th>Secretary</th><th>Terms of Reference</th><th>Named membership</th><th>Occurences</th><th>Room</th><th>Date</th><th>Time</th></tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['title']. "</td>";
echo "<td>" . $row['chairman']. "</td>";
echo "<td>" . $row['secretary']. "</td>";
echo "<td>" . $row['termsOfReference']. "</td>";
echo "<td>" . $row['occurences']. "</td>";
echo "<td>" . $row['room']. "</td>";
echo "<td>" . $row['date']. "</td>";
echo "<td>" . $row['time']. "</td>";
echo "</tr>";
}
echo "</table>";
include 'library/closedb.php';
?>
do i need both table id somewhere?
I'd doubt that date and time are columns in your rooms table, so they shouldn't be part of the JOIN condition. Try:
SELECT *
FROM meetings m
INNER JOIN rooms r
ON m.room = r.room
By "Using" keyword it will check both tables by column names. It will check inner join on Ist condition then it will get left join on next columns if result not found.
it's bad practice to use "Using" keyword.
Simplify joins by USING.
By
-Multiple columns
-Single column

Categories