Retrieve search results | PHP & SQL - php

I have a table created with all the fields necessary like (ID, Name, surname, etc.)
In search php file, when you type the ID it shows you all the information corresponding of this ID, e.g. (ID=1, name=Jack)
MY IDEA: When i do a custom search, inside the php I want to add a link to another php file that shows the same search result but with additional info.
QUESTION: How can I call to a custom search result from other php file?
Regarding this example, If I search for ID=2, I want to link to another php file "Extrainfo.php" that shows more info of that custom search.
Here is the code I used:
//database connection
global $conn;
$servername = "localhost"; //host name
$username = "root"; //username
$password = ""; //password
$mysql_database = "info"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
if(isset($_GET['idNumber']))
{
$IDNUMBER =$_GET['idNumber'];
$stmt = $conn->prepare("select * from madea where idNumber=? ");
$stmt->bind_param('s',$IDNUMBER);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count>0)
{
$result =$val->fetch_assoc();
echo $result['idNumber'];
echo $result['name'];
}
else
{
echo "identification_number not Match";
}
$stmt->close();
$conn->close();
// Probably need to save the variable to call in the other php file?
$idNumber = $result['idNumber'];
}
?>
Extrainfo

This is what I can show you.
You 1st php,
if(isset($_GET['idNumber']))
{
$IDNUMBER =$_GET['idNumber'];
$stmt = $conn->prepare("select * from madea where idNumber=? ");
$stmt->bind_param('s',$IDNUMBER);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count>0)
{
$result =$val->fetch_assoc();
echo $result['idNumber'];
echo $result['name'];
echo "More Info";
}
else
{
echo "identification_number not Match";
}
$stmt->close();
$conn->close();
// Probably need to save the variable to call in the other php file?
$idNumber = $result['idNumber'];
}
Now I'm using AJAX and Jquery so please link the appropriate libraries.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.moreInfo', function(){
$.ajax({
url: 'moreInfo.php',
type: 'post',
data: {
'idNumber': $('.moreInfo').prop('id')
}
}).then(function (response) {
$('#morInfoDiv').html(response);
});
})
})
</script>
The moreInfo.php,
if(isset($_POST['idNumber']))
{
$IDNUMBER =$_GET['idNumber'];
$stmt = $conn->prepare("select * from madea where idNumber=? ");
$stmt->bind_param('s',$IDNUMBER);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count>0)
{?>
Name:<? echo $result['Name']; ?><br>
Address:<? echo $result['address']; ?><br>
Date of Birth:<? echo $result['dob']; ?><br>
<?php }
else
{
echo "identification_number not Match";
}
$stmt->close();
$conn->close();
}
Now in your 1st php file can have a DIV which will show the response from the moreInfo.php
<html>
<body>
<div id="morInfoDiv"></div>
</body>
</html>
AJAX script will send the data in post method then capture the response text from the 2nd PHP and add it to the DIV ided as "moreInfo".

Well I finally do it by another way.
result.php only added an href that redirects to a moreinfo.php but with the query string of the id number.
Download PDF INFO
And here comes the other part of code in moreinfo.php
At first, get the id number on query string that it previously redirected by the link and get it into a variable to use it after in the sql query
$reportNumber = $_GET['idNumber'];
$result = mysqli_query($con,"SELECT * FROM madea where reportNumber='".$idNumber."'");
And the rest, only show the results what I really need:
while($row = mysqli_fetch_array($result))
{
$html .= '<td>'.$row['idNumber'].'</td><td>' . $row['Name']. '</td>';
}
Hope it helps to further issues. So appreciated for all the help!! :)

Related

Trying to compare a value from the database from the url after the?

I'm trying to get a value from the database and compare it with whatever id href was set. But nothing happens.
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "products";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo <<<EOT
<br>
<form action='index.php?$id' method="POST">
<input type='submit' name="submit" value="more">
</form>
EOT;
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
while($row = $result->fetch_assoc()) {
if ($_SERVER["QUERY_STRING"] == $row) {
echo 'you clicked something from the database' . $id;
}
}
}
$conn->close();
?>
Trying to eventually get a value from the database then individually show a description if the more href is clicked.
your answer has a high time complexity you can easily make you
SQL query
SELECT id FROM items WHERE id = ?
and if the rows number is 0 this is mean there is no record with this id
you can check row's number from num_rows
You will never see "you clicked something from the database" message because you already fetched the result from your query in the first loop, check this question why-cant-i-loop-twice-on-mysqli-fetch-array-results
An option is to save the result in an array to use it later in your second loop
//your first loop
$savedRows = [];
while($row = $result->fetch_assoc()) {
$savedRows[] = $row;
//the rest of your code
}
// ......
// your second loop
if (isset($_POST['submit'])) {
foreach($savedRows as $row) {
if ($_SERVER["QUERY_STRING"] == $row['id']) {
echo 'you clicked something from the database ' . $id;
}
}
}
Also note that if this is your actual code, you need to make the closing identifier of your herodoc EOT; the first character on it's line, otherwise the rest of the file will be part of this string

Having problems retrieving from mysql to populate form

I'm having a problem getting a result from my mysql database and getting it to popular a form. Basically, i'm making an item database where players can submit item details from a game and view the database to get information for each item. I have everything working as far as adding the items to the database and viewing the database. Now i'm trying to code an edit item page. I've basically reused my form from the additem page so it is showing the same form. At the top of my edititem page, I have the php code to pull the item number from the url as the item numbers are unique. So i'm using a prepared statement to pull the item number, then trying to retrieve the rest of the information from the database, then setting each information to a variable. Something is going on with my code but I can't find any errors. I entered a few header calls to debug by putting information in the url bar...But the headers aren't even being called in certain spots and im not getting any errors.
In the form, I used things like
<input name="itemname" type="text" value="<?php $edit_itemname?>">
and nothing is showing in the textbox. I'm fairly new to php and it seems much more difficult to debug than the other languages i've worked with..Any help or suggestions as far as debugging would be greatly appreciated. I posted my php code below as well if you guys see anything wrong...I shouldn't be having issues this simple! I'm pulling my hair out lol.
Thanks guys!
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
}else{
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
}else{
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
}else{
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
header("Location: edititem.php?testing");
}
}
}
}
?>
To get the value of $edit_itemname into the output you should be using <?= not <?php. Saying <?php will run the code, so basically that is just a line with the variable in it. You are not telling it to print the value in the variable.
If your whole line looks like:
<input name="itemname" type="text" value="<?= $edit_itemname?>">
That should give you what you are looking for. The <?= is the equivalent of saying echo $edit_itemname;
If you don't like using <?= you could alternatively say
<input name="itemname" type="text" value="<?php echo $edit_itemname; ?>">
Your code should be change to a more readable form and you should add an output - I wouldn't recomment to use <?= - and you need to choose what you're going to do with your rows - maybe <input>, <table> - or something else?
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
} // no else needed -> exit()
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
} // no else needed -> exit()
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
} // no else needed -> exit()
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
// does not make sense here: header("Location: edititem.php?testing");
// show your data (need to edited):
echo "Name: " + $edit_itemname + "<br/>";
echo "Area: " + $edit_itemarea + "<br/>";
echo "Comment: " + $edit_itemcomments + "<br/>";
// end of current row
echo "<hr><br/>"
}
?>

Display result of Pdo

Hi i have an slight problem i'm trying top geht tow Results of My pdo query and Print Them but No such luck i've probably just Made a Stupid mistake i'm Not seeing The query seems to be finde so it does make a difference if the name is in the database (and it makes a difference if you put it in quotes) probably the variables are getting a null value or something...
$username="xxx";
$firstname="xxx";
$check=0;
if (isset($_GET['u'])){
$username=strip_tags(#$_GET['u']);
if (ctype_alnum($username)){
$check=$stmt=$link->prepare("SELECT * FROM
users WHERE username = ?");
$stmt->execute(array($username));
$check=$stmt->fetchAll();
if(count($check)==1){
$get=$stmt->fetch(PDO::FETCH_BOTH);
echo "$get";
$username =$get["username"];
$firstname = $get["first_name"];
}else{
echo "<h2> User does not exist!</h2>";
exit();
}
}
}
?>
<h2>Profilepage for: <?php echo "$username"; ?></h2>
<h2>First name: <?php echo "$firstname"; ?></h2
$stmt->fetchAll() is fetching all the results of the query. Once this is done, there are no more results available for $stmt->fetch() to fetch. You should get the data from the $check array.
if (count($check) == 1) {
$get = $check[0];
$username = $get["username"];
$firstname = $get["first_name"];
} else {
echo "<h2> Username does not exist </h2>";
exit();
}
Or you could just replace the fetchAll with fetch.
$stmt->execute(array($username));
$get = $stmt->fetch(PDO::FETCH_ASSOC);
if ($get) {
$username = $get["username"];
$firstname = $get["first_name"];
} else {
echo "<h2> Username does not exist </h2>";
exit();
}
Also, echo "$get" makes no sense. $get is an array, you can't echo it, you need to use print_r($get) or var_dump($get).

posting a search result in php

I have created a search using php so that when a user is logged in they can search for other users and add them as a friend. When the user clicks the add as friend button I would like to post the username of the user that is logged in and the username of the user in the search result to a database table called friend_request.
Here is my code
<?php
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$search = "%$search%";
if ($stmt = $db->prepare("SELECT username, name, location, gender, date_of_birth, url FROM Users WHERE name LIKE ?")){
$stmt->bind_param("s", $search);
$stmt->execute();
$stmt->bind_result($username, $name, $location, $gender, $date_of_birth, $picture);
$stmt->store_result();
$count = $stmt->num_rows;
if ($count == 0) {
$output = "There was no search results!";
} else {
while ($stmt->fetch()) {
$output .='<form action="#" method="post"><div class="row"><div class="col-sm-3">'.$name.'<br>'.$location.'<br>'.$gender.'<br>'.$date_of_birth.'</div>';
$output2 = '<div class="col-sm-3"><img src="upload/'.$picture.'"width="180" height="144" /></div>';
$output3 = '<input type="submit" name="addfriend" value="Submit" /></div></form>';
}
}
}
}
if(isset($_POST['addfriend'])) {
$user_from = $_SESSION['username'];
$user_to = $_POST['username'];
if ($stmt = $db->prepare("INSERT INTO `friends_request`(`user_to`, `user_from`) VALUES (?,?)")){
$stmt->bind_param("ss", $user_to, $user_from);
$stmt->execute();
}
}
?>
When I run my code I get the following message
Notice: Undefined index: username in /Applications/MAMP/htdocs/student_connect/header.php on line 51
It is simple.
It says $_SESSION['username']; hasn't been set, so look for the line of code where you expect you'd set it. I guess it might be in some other file (maybe to be executed after a login-form filling..?)
You need to start Debugging your code.....
Try adding this line after "$user_from = $_SESSION['username'];"
if(!$user_from)
{
echo "<pre>";
var_dump($_SESSION);
echo "<pre>";
}
Run your code and paste the results here - we can then start to determine what information is held in SESSION.
This is something you have to do when code doesn't do what expected, check your variables and see whats missing before heading to Stack. We are here to help, but need all info possible.

Not able to insert the data from url to database in php

final.php
Here I am trying to get the data from the url using GET method and trying to insert into the database. I was able to insert the data for first few rows after that the data is not inserted. Can anyone help me regarding this?
when I try to run the url: www.myii.com/app/final.php?name=123&glucose=3232...
the data is not inserting.
<?php
include("query_connect.php");
$name = $_GET['name'];
$glucose = $_GET['glucose'];
$temp = $_GET['temp'];
$battery = $_GET['battery'];
$tgs_a = $_GET['tgs_a'];
$tgs_g = $_GET['tgs_g'];
$heartrate = $_GET['heartrate'];
$spo2 = $_GET['spo2'];
$rr = $_GET['rr'];
$hb = $_GET['hb'];
$ina22 = $_GET['ina22'];
$accucheck = $_GET['accucheck'];
$isactive = $_GET['isactive'];
$address = $_GET['address'];
$deviceno = $_GET['deviceno'];
$sql_insert = "insert into query (name,glucose,temp,battery,tgs_a,tgs_g,heartrate,spo2,rr,hb,ina22,accucheck,isactive,address,deviceno) values ('$name','$glucose','$temp',$battery','$tgs_a','$tgs_g','$heartrate','$spo2','$rr','$hb','$ina22','$accucheck','$isactive','$address','$deviceno')";
mysqli_query($sql_insert);
if($sql_insert)
{
echo "Saving succeed";
//echo $date_time;
}
else{
echo "Error occured";
}
?>
Query_connect.php
This is my database config php file.
<?php
$user = "m33root";
$password = "me3i434";
$host = "localhost";
$connection = mysqli_connect($host,$user,$password);
$select = mysqli_select_db('miiyy',$connection);
if($connection)
{
echo "connection succesfull<br>";
}
else {
echo "Error";
}
?>
Make sure that all columns can contain NULL so that not filled fields will stay NULL instead of throwing an error.
Try below to see mysql error:
mysql_query($sql_insert);
echo mysql_error()
Try these
In SQL
Change the table name of query to some other name. Because "query" is reserved in SQL
In code
if (!mysqli_query($con,$sql_insert ))
{
echo("Error description: " . mysqli_error($con));
}
else
{
echo "Success";
}
Use mysqli_error() function

Categories