I’m fairly new to PHP/MySQL/jQuery and I’m stuck on this one piece of a large project.
Coding a live seach box that I’d like to return Names or Phone Numbers already in the database based on user input. I can get it to output just Names or just Phone Numbers by changing $variable
to “Name” or “Phone”, but I’ve been unable to come up with a working solution to dynamically do either sumultaniouly. I’ve been researching/troubleshooting for hours with if/else using is_numeric()
and/or is_nan()
, setting a global
variable, reworking the query many different ways, and done hours of research. Any suggestions are greatly appreciated!
inventory.php:
<?php
// Session Start
session_start();
// If the user not logged in, redirect to the login page
if (!isset($_SESSION['loggedin'])) {
header('Location: index.html');
exit;
}
//Connect to database
require_once('connection.php');
if(isset($_REQUEST["term"])){
$variable = "Name";
// Prepare a select statement
$sql = "SELECT $variable FROM vendor WHERE $variable LIKE ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_term);
// Set parameters
$param_term = $_REQUEST["term"] . '%';
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$vendresult = mysqli_stmt_get_result($stmt);
// Check number of rows in the vendresult set
if(mysqli_num_rows($vendresult) > 0){
// Fetch vendresult rows as an associative array
while($row = mysqli_fetch_array($vendresult, MYSQLI_ASSOC)){
echo "<p>" . $row["$variable"] . "</p>";
}
} else{
echo "<p>No Match Found - Vendor Setup</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// close connection
mysqli_close($conn);
?>
HEAD portion of inventoryentry.php:
<script>
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var vendresultDropdown = $(this).siblings(".vendresult");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
vendresultDropdown.html(data);
});
} else{
vendresultDropdown.empty();
}
});
// Set search input value on click of vendresult item
$(document).on("click", ".vendresult p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".vendresult").empty();
});
});
</script>
BODY portion of inventoryentry.php:
<div class="search-box"><input type="text" autocomplete="off" placeholder="Vendor Lookup" /><div class="vendresult"></div></div>
Code does work, but not in the way I’d like.