PHP Search Feature not printing results - php

This is my code :
if(isset($_GET['search'])) {
$search_value= $_GET['searchbox'];
echo "Search results for $search_value";
print "<br><br>";
$query="
SELECT idemp,sn
FROM employee
WHERE idemp like '%search_value%'
OR sn like '%search_value%'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc($query)) {
$idemp=$row->idemp;
$sn=$row->sn;
echo $row['$idemp'];
echo $row['$sn'];
}
}
};
it didn't return matching result even if there is an equivalent in the database... help tnx...

Your'e not including the variable in the query, you're including only its name (without the $?).
$query="SELECT idemp,sn FROM employee
WHERE idemp like '%$search_value%' OR
sn like '%$search_value%'";
Since you're using mysqli, it would be better to bind the values either way, since it will normalize the input and prevent injection. Here's an example:
$conn->prepare("SELECT idemp,sn FROM employee
WHERE idemp like ? OR
sn like ?");
$conn->bind_params('ss', $search_value, $search_value);
$conn->execute(); // <-- returns the query results

Related

Querying each element of an array and displaying them as individual data

I have an array which looks like this
"76561198086947554", "76561198133402236"
I need to query each value individually and display the queried data on a page
$pid would be a single value of the array above which I am wanting to query indiviually
$sqlget = "SELECT * FROM players WHERE pid='$pid'";
$result = $conn->query($sqlget);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$name = $row["name"];
echo "<div>
Members: ".$name."
<div>";
}
}
I am happy to try explain it a bit more if you would like me to.
First you use mysql query that have issues with sql injection and is outdated.
Second, if i have understand you need in your WHERE clause the pid value to be in the array you have so your query should be like this:
$your_array = "76561198086947554, 76561198133402236";
$sqlget = " SELECT * FROM players WHERE pid IN ('".$your_array."') ";
// here you check if pid is in array values
... // the other code
Hope it helps and try to convert your code using PDO statements or mysqli.

How to get SELECT EXISTS() query value

I have this php code:
$query = $database->query("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID')";
if($query == 0){
echo "not registered";
}elseif($query == 1){
echo "registered"
}
If I'm not wrong, the query is suppose to return 0 or 1 and it works in my SQLite manager. What is the correct way on getting that value in Php and use it in IF ELSE statement?
If you only need a single value, you can use querySingle:
$result = $database->querySingle("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID'");
Otherwise, with normal queries, the result returned by ->query isn't actually the data itself, but an identifier you would use to get data from the database:
$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}

How to set result SQL distinct query to one or different variables?

I'm creating a mobile library app, and for one function of the app I am trying to receive the bookID for all books checked out by a certain user. I would like to be able to echo back the results from the query in a string format (preferably with spaces in between each separate book id) so I can deal with the data later on within the app.
Many of the answers I have found online have simply shown how to execute the query, but not how to use the data afterwards. Sorry if this is a simple question to answer, I am a huge novice.
<?php
require "conn.php";
$email = $_POST["email"];
$mysql_qry = "SELECT * FROM user_data WHERE email like '$email'";
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID LIKE $user_id ORDER BY bookID DESC";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$result2 = mysqli_query($conn, $mysqlqry2);
}
else
{
echo "Error, user name not found";
}
$conn->close;
?>
You could append your results into an array and display values using implode():
<?php
require "conn.php";
$email = $_POST["email"]; // You may test here : if (isset($_POST['email']))
$mysql_qry = "SELECT * FROM user_data WHERE email = '$email'";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID = $user_id ORDER BY bookID DESC";
$result2 = mysqli_query($conn, $mysql_qry2);
if(mysqli_num_rows($result2) > 0)
{
$ids = [];
while ($row = mysqli_fetch_assoc($result2)) {
$ids[] = $row['bookID'] ;
}
echo implode(" ", $ids) ; // print list of ID
}
else
{
echo "No books checked out!";
}
}
else
{
echo "Error, user name not found";
}
$conn->close;
NB: I used your code here, but, you should have to look to parameterized queries to prevent SQL injections.
Your query $mysql_qry2 should be defined after to get $user_id.
Your LIKE $user_id could be replaced by =.
First thing first, always sanitize your data:
$email = filter_var( $_POST['email'], FILTER_SANITIZE_EMAIL );
$user_id = preg_replace( "#[0-9]#", '', $row['user_id'] );
Use
DISTINCT bookID instead of DISTINCT(bookID)
From your query: $mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY bookID DESC";
If you're not getting any result or the returned result is empty but the user_id does exist, then I think the query format is wrong.
What you should do instead
Change the ORDER BY: The query may be correct but mysql returned an empty result because the result order does not match.
Try this
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY userID DESC";
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY `primary_key_here` DESC";
Replace <strong>`primary_key_here`</strong> with the primary key name.
Run the query without conditionals and inspect the result
$query = mysqli_query( $conn, "SELECT bookID FROM books_checked_out DESC" );
var_dump( $query );
Use the result to inspect the rest of the query.
Rather than using your own protocol/format use something like JSON or xml in your response to the request.
This will give you better maintainability in the long run and allow you to easily handle the response in the browser with javascript, and most browsers will give you a nice display of JSON objects in the dev console.
You'll have to extract the user id from the result of the first query or you could do a joined query instead.
$email = validate($POST['email']); //where validate() will try to prevent sql injection
//joined query
$query =
" SELECT bookID FROM user_data
INNER JOIN books_checked_out on user_data.user_id = books_checked_out.userID
WHERE user_data.email='$email'
";
//not sure whether that should be user_id or userID looks like you have mixed conventions
//books_checked_out.userID vs user_data.user_id ... check your database column names
//loop through results
// may be empty if user email doesn't exist or has nothing checked out
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$response[] = ['bookID'=>$row['bookID']];
}
echo json_encode($response);
When receiving the result in php you can use json_decode() or in javascript/ajax it will automatically be available in your result variable.
if things aren't working as expected it can be a good idea to echo the actual sql. In this case
echo 'SQL IS: '.$query;
and test it against your database directly (phpmyadmin/MySQL-Workbench) to see if you get any results or errors.

php search printing all items even without inputting any character

This is my search code,it works but when I got to print go even without entering any character. It still searches. Worst, it prints all the items in the database what would I do. Thanks.
if(isset($_GET['search'])) {
$search_value= $_GET['searchbox'];
//$sql="SELECT idemp,sn FROM employee
//WHERE idemp like '%$search_value%' OR
//sn like '%$search_value%'";
$sql = "select * from employee where (id_no like '%$search_value%' OR sn like '%$search_value%')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "'$result->num_rows' result/s for '$search_value'";
print "<br><br>";
You might need to change your if condition as
if(isset($_GET['search']) && !empty($_GET['searchbox'])){
// do search
}
if(isset($_GET['search'])) will return true because it is set to empty string.
if(isset($_GET['search']) && $_GET['search'] )
is the condition you are looking for
First check that your getting any string or not,
Run your query only when you got something.
if(isset($_GET['searchbox']) && $_GET['searchbox'] != ''){
$search_value= $_GET['searchbox'];
$sql = "select * from employee where (id_no like '%$search_value%' OR sn like '%$search_value%')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "'$result->num_rows' result/s for '$search_value'";
print "<br><br>";
}

Pass the parameter into query

I'm new in php and PDO. I just wondering how to pass the parameter into my query,
I already assign $a="January 2010 Semester"; and to pass to my query. But when i echo the query, it display like this.
SELECT Nama,Intake,matricNo, FROM VMESubjectGrade where Intake="$a" GROUP BY Nama
It Should be display like this
SELECT Nama,Intake,matricNo, FROM VMESubjectGrade where Intake="January 2010 Semester" GROUP BY Nama
This is my code,
Hope can advise,
Special Thanks.
$a="January 2010 Semester";
mysql_select_db("school", $con);
$query2='SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake="$a"' ;
$query2testing = mysql_query($query2);
try {
$db = new PDO('mysql:host=localhost;dbname=school;charset=utf8', 'root', 'xxx');
} catch (PDOException $e) {
echo $e->getMessage();
}
//get the SubCodes
$stmt = $db->query('SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake="$a"');
$row_count = $stmt->rowCount();
//generate pivot sql statement
$sql = 'SELECT Nama,Intake,matricNo, ';
$dynamic_fields = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$dynamic_fields[] = $row['SubCode'];
$sql .= "MAX(CASE SubCode when '{$row['SubCode']}' then grade end) AS {$row['SubCode']}";
if ($row_count > 1) {
$sql .=',';
}
$row_count--;
}
$sql .= ' FROM VMESubjectGrade where Intake="$a" GROUP BY Nama ';
echo $sql;
THIS PROBLEM ALREADY SOLVE.
I know you think you've already solved the problem, but please read this!!
One of the main advantages to PDO is the ability to do parameterized queries, which will sanitize your database inputs. As you currently have it, you're vulnerable to SQL injection!
If someone passes a variable that you use in the query, and you don't sanitize it, you will end up in big trouble. Suppose $a was set to "; DROP TABLE VMESubjectGrade;--. What does your query become? It becomes this:
SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake=""; DROP TABLE VMESubjectGrade;--"
The day someone tries something like this will be a very bad day for you, unless you properly sanitize your database inputs.
Try doing your queries like this:
$query = 'SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake = :a';
$stmt = $db->prepare($query);
$stmt->execute(array(':a' => $a));
This will pass the parameter in to the query and sanitize the variable in case it actually comes from user input.
:a acts as a placeholder for a parameter in your query and you assign the value of it when you execute.
you should concact that string into query like this
echo $query2='SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake='.$a.'';
$query2testing = mysql_query($query2);
output will be like this-> SELECT DISTINCT(SubCode) FROM VMESubjectGrade where Intake=January 2010 Semester

Categories