Searching multiple tables and columns with a keyword in php [duplicate] - php

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
I am building an android application which uses mysql database as backend. I am trying to search through tables and multiple columns with a keyword and return them to the android app using php in a json format.
I tried a sample code i got from this question but it doesn't seem to work.
Here is my php code
<?php
require "conn.php";
$key = $_POST["key"];
$array = array();
$mysql_query = "(SELECT *, 'home' AS type FROM home WHERE food_name LIKE '%" . $key . "%' OR descrip LIKE '%" . $key ."%' OR user_name LIKE '%" . $key ."%'
UNION
SELECT *, 'c4c' AS type FROM cook4cash WHERE food_name LIKE '%" . $key . "%' OR descrip LIKE '%" . $key ."%' OR user_name LIKE '%" . $key ."%'
UNION
SELECT *, 'vendor' AS type FROM vendors_info WHERE user_name LIKE '%" . $key . "%'
UNION
SELECT *, 'customer' AS type FROM customers_info WHERE user_name LIKE '%" . $key . "%')";
mysql_query($query);
$result = mysqli_query($conn, $mysql_query);
if(mysqli_num_rows($result) > 0){
session_start();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
//echo json_encode($row);
}
foreach($array as $new_array){
$new_array['id'] . '<br/>';
$new_array['food_name'] . '<br/>';
$new_array['descrip'] . '<br/>';
$new_array['price'] . '<br/>';
$new_array['quantity'] . '<br/>';
$new_array['image_url'] . '<br/>';
$new_array['user_name'] . '<br/>';
$new_array['profile_pic'] . '<br/>';
$new_array['delivery_time'] . '<br/>';
$new_array['delivery_cost'] . '<br/>';
$new_array['location'] . '<br/>';
$new_array['email'] . '<br/>';
}
echo json_encode(array("userInfo" => $array));
} else {
echo "No data was found";
}
?>
When i use postman to test, it gives the error code 500 (Internal Server Error).
I want to know what is wrong with this code.

Did you check PHP error_logs? I guess reason of the problem is line 14. You're using mysqli_* methods but on line 14, you had tried to use a mysql_* method. I think you should remove the code on this line and try again.

Related

Search result page leading to a specific page [up]

I am creating a database website wherein there is a search bar then it will lead to a search results page (in table form). The user will then select a specific result that would lead to a custom webpage for that result. Is there a way to do that in PHP/MYSQL?
Here is my PHP code:
<?php
include "databaseconnect.php";
$keywordfromform = $_GET["Search"];
$sql = ("SELECT titleID, authorsID, yearID, subjectID
FROM researchpapertable
WHERE titleID LIKE '%" . $keywordfromform . "%'
OR authorsID LIKE '%" . $keywordfromform . "%'
OR yearID LIKE '%" . $keywordfromform . "%'
OR subjectID LIKE '%" . $keywordfromform . "%'
");
$result = $mysqli->query($sql);
if ($result-> num_rows>0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<tr><td>'. $row["titleID"]."</td><td>". $row["authorsID"]."</td><td>". $row["yearID"]."</td><td>". $row["subjectID"]."</td></tr>";
}
} else {
echo "<tr><td> 0 results </td><td> 0 results </td><td> 0 results </td><td> 0 results </td><tr>";
}
$mysqli->close();
?>
I placed a <a href="indivpage.php"> in the column where they will select the title of their choice. What should I place there for it to lead to its specific page? I am not sure what I should search for in order to search for similar tutorials/code. If there are similar questions/code to this, it would help a lot. Thank you in advance!
You would send a unique identifier as a parameter to your page. Like this:
echo '<tr><td>' . $row["titleID"] . '...etc...</td></tr>';
Then in your indivpage.php you would use $_GET['title_id'] to fetch all the details from the database.
Let me add to this that there is very much wrong with the code you wrote. To begin with I would suggest to read about SQL injection

Re-writing several individual SQL query's into one [duplicate]

This question already has answers here:
MySQL - Counting two things with different conditions
(4 answers)
Closed 2 years ago.
I have a database where I'm displaying numbers of rows from different columns of a table, as statistics for a site. In pure text, it looks like this (english translation):
"At the moment, there are 86 questions registered. 16 are in the category of history, 6 in the category of geography."
My PHP script is pretty simple:
$question_query = mysqli_query($conn, 'SELECT Q_id FROM questions');
$question_result = mysqli_num_rows($question_query);
$historie_query = mysqli_query($conn, "SELECT Q_id FROM questions WHERE category LIKE '%Historie%'");
$historie_result = mysqli_num_rows($historie_query);
$geografi_query = mysqli_query($conn, "SELECT Q_id FROM questions WHERE category LIKE '%Geografi%'");
$geografi_result = mysqli_num_rows($geografi_query);
echo '<h3>' . 'For øyeblikket er det ' . '<b>' . $question_result . '</b>' . ' spørsmål i databasen:' . '</h3>';
echo '<ul>' . '<li>' . '<b>' . $historie_result . '</b>' . ' historie-spørsmål.' . '</li>' ;
echo '<li>' . '<b>' . $geografi_result . '</b>' . ' geografi-spørsmål.' . '</li>' . '</ul>';
This works well, but right now it's only doing 3 queries. In the future, it will probably be about 10 or 15 queries.
I've tried to join these into one, but it's only outputting the first query:
$query = "SELECT Q_id FROM questions";
"SELECT Q_id FROM questions WHERE category LIKE '%Historie%'";
"SELECT Q_id FROM questions WHERE category LIKE '%Geografi%'";
$result = mysqli_query ($conn, $query);
$count = mysqli_num_rows($result);
print_r ($count);
I figured a while loop might be able to solve that, but when I replace the print_r with the while loop, I get an undefined variable error for the different row counts ($question_count, $historie_count, $geografi_count):
while ($row = mysqli_fetch_assoc($result)) {
$row[0] = $question_count;
$row[1] = $historie_count;
$row[2] = $geografi_count;
print_r ($question_count . '</br>' . $historie_count . '</br>' . $geografi_count);
}
How could I go about making this into one query? And, is that desirable, or is it better to keep the queries separated?
Thanks in advance!
Use conditional aggregation:
select
count(*) question_count,
sum(category like '%Historie%') historie_count,
sum(category like '%Geografi%') geografi_count
from questions

how to perform a multi sql search via php in one field

i am using this sql search to find a title and artist in my database. I have on field containing infos like "ref.1570 title artist.mp4". When I do the search it works but in one direction only, i would like to get the result whatever the order i do the search... to be more precise if i search "title artist" no problem i found it. If i search "artist title" no way ... how can you help me making php sql search both directions ?
Best regards and thank you for your help.
Phil
i am using this code :
if ($search != null) {
$sql = 'SELECT * FROM `catalog` WHERE (`file`LIKE "%' . $search . '%")';
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE (`file`LIKE "%' . $search . '%")';
}
Why don't you split keyword $search with space and append with Like statement in the query. Eg:
if ($search != null) {
$keywords=explode(" ",$search);
$sql = 'SELECT * FROM `catalog` WHERE 1=1'; // just to append OR condition.This won't affect anything as the condition will always be true.
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE 1=1 ';
foreach($keywords as $key){
if(!empty($key)){
$sql.=' And file Like \'%'.$key.'\%';
$sqlCount.=' And file Like \'%'.$key.'\%';
}
}
}
I believe this will work as you expected.
I think you won't get around a foreach:
if ($search != null) {
$arrayOfSearchTerms = explode(' ', $search);
$sql = 'SELECT * FROM `catalog` WHERE ';
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE ';
$termNumber = 0;
foreach ($arrayOfSearchTerms as $term) {
$addingSql = '';
if ($termNumber > 0) {
$addingSql = ' OR ';
}
$addingSql .= '(`file` LIKE "%') . $term . '%")';
$sql .= $addingSql;
$sqlCount = $addingSql;
$termNumber++;
}
}
You need to iterate over your search terms and add this terms into your 'LIKE'-Statement
you can try this research: it does a LIKE %word% for every word. If you want more powerfull research you should use tools like elasticsearch etc...
This way you could do:
$parts = explode(" ",$search)
$queryParts = array();
foreach ($parts as $part) {
$queryParts[] = `artist`LIKE "%' . $part . '%" ;
}
// this way we can have like %artist% AND like %title%
$querySearch= implode(" AND ", $queryParts);
$sql = 'SELECT * FROM `catalog` WHERE (". $querySearch .")';
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE (`". $querySearch .")';
you have solved my problem i know now hos to correctly explode a request into variables ..
$search = $name;
$explode=explode(" ",$search);
print_r (explode(" ",$explode));
and then i use my sql request like this
$sql = 'SELECT * FROM `catalog` WHERE (`idc` LIKE "%' . $search . '%" OR `file` LIKE "%' . $search . '%" OR `title` LIKE "%' . $explode[0] . '%" AND `artist`LIKE "%' . $explode[1] . '% " OR `artist`LIKE "%' . $explode[0] . '%" AND `title`LIKE "%' . $explode[1] . '%")';
and it is working !
COOL
Use the multi query functions,
in mysqli should be : mysqli_multi_query();
More info on : Mysqli Multiquery

multiple field search form displaying entire database [duplicate]

This question already has answers here:
Search Form with One or More (Multiple) Parameters
(2 answers)
Closed 7 years ago.
I am trying to create a database with multiple fields for searching but it is displaying the entire database if there is an empty field. i suspect it is because of the OR's in the query and i am not sure how to fix it.
<?php
if (isset($_POST['Submit']))
{
$con = mysqli_connect();
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$surname = $_POST['surname'];
$firstname = $_POST['firstname'];
$maiden = $_POST['maiden'];
$birth = $_POST['birth'];
$death = $_POST['death'];
$keyword = $_POST['keyword'];
$sql = "SELECT * FROM obits WHERE surname LIKE '%" . $surname . "%' OR firstname LIKE '%" . $firstname . "%' OR maiden LIKE '%" . $maiden . "%' OR birth LIKE '%" . $birth . "%' OR death LIKE '%" . $death . "%' OR obittext LIKE '%" . $keyword . "%'";
$result = mysqli_query($con, $sql);
further down i have this:
if (isset($result) && $result->num_rows > 0);
then follows the table etc. i think i have all the pertinent info here. any suggestions? please use english rather than programmer, i am quite new at this. thanks in advance!
Let's look at one of the conditions:
surname LIKE '%" . $surname . "%'
Assuming, $surname is Miller here, you select all rows that have a surname like %Miller%. The % signs are wildcards, which can basically stand for anything. This means you are selecting all rows where the surname contains Miller with any string before or after it, including empty ones.
Now, if Miller would be empty in this case, you are looking for %%, so an empty string with anything before or after it -- so really any possible string. As a result, every row will be selected.
Since this is true not only for the surname, but for any of the columns, leaving any of the criteria blank will result in all rows being selected.
Find more info on SQL Wildcards.
To skip empty values in your where clause, you can build it dynamically:
$condition = "WHERE";
if(!empty($surname)){
$condition .= "surname LIKE '$surname' OR";
}
if(!empty($firstname)){
$condition .= "firstname LIKE '$firstname' OR";
}
// ...
$sql = "SELECT * FROM obits " . $condition;
Note:
There will be a trailing OR in the condition that you will have to remove.
If all conditions are blank, this will also lead to an error.
But it should give you an inpiration! :-)
Side Note:
You should look into prepared statements. Passing POST variables directly into an SQL statement is highly dangerous.

mysqli_query don't work in PHP

Im trying to make an easy Select from the db and save the results in an array.
$query = "SELECT ID FROM Publikationen WHERE Personen LIKE '%; " . $autor2 . "%';";
echo($query);
// get IDs
$res = mysqli_query($link,$query );
$i = 0;
while ($row = mysqli_fetch_assoc($res)){
echo($row['ID']);
$IDarray[$i]= $row['ID'];
$i++;
}
The $autor2 variable is an Name like: "Doe, John".
The code seems to not go in the loop, and mysqli_error after the loop is null so it seems im not getting results from the db.
When im copying the echo from $query in phpMyAdmin it works fine. Also when im using a Name instead $autor2 it also works fine and im getting my whole Array.
$query = "SELECT ID FROM Publikationen WHERE Personen LIKE '%" . $autor2 . "%'";
write this code.
As far as I can see in the SQL query, there's a syntax error.
You wrote :
SELECT ID FROM Publikationen WHERE Personen LIKE '%; " . $autor2 . "%';
but it should have been :
SELECT ID FROM Publikationen WHERE Personen LIKE '%" . $autor2 . "%';
Hope it helps!
Remove the semicolon from the query.
$query = "SELECT ID FROM Publikationen WHERE Personen LIKE '% " . $autor2 . "%'";
Simply use this -
$query = "SELECT ID FROM Publikationen WHERE Personen LIKE '%$autor2%'";
If the semicolon is important then use it but use the $author2 variable just inside single quote (' ').

Categories