posting a search result in php - 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.

Related

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/>"
}
?>

Retrieve search results | PHP & SQL

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!! :)

PHP - Form error alerts displays on page load

i am a newbee and just learning along the way. I have two forms on a page (I have only shown one of them as the other form is the same code with different variables). Both their error messages display on page load. How can I stop this?
I have read multiple posts regarding this but I still cannot find a solution.
<?php
if(isset($_POST['Update'])) {
$c_fname = $_POST['fname'];
$c_lname = $_POST['lname'];
$c_email = $_POST['email'];
$c_phone = $_POST['phone'];
// Save $_POST to $_SESSION
//query
$insert_det = "INSERT INTO Cus_acc_details(CUS_Fname,CUS_Lname,Cus_Email,CUS_Phone)
VALUES (?,?,?,?)
ON DUPLICATE KEY
UPDATE
Cus_acc_details.CUS_Fname = '$c_fname',
Cus_acc_details.Cus_Lname = '$c_lname',
Cus_acc_details.Cus_Email = '$c_email',
Cus_acc_details.CUS_Phone = '$c_phone'";
$stmt = mysqli_prepare($dbc, $insert_det);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sssi', $c_fname, $c_lname, $c_email, $c_phone);
/* execute query */
$r = mysqli_stmt_execute($stmt);
// if inserted echo the following messges
if ($r) {
echo "<script> alert('Saved')</script>";
}
} else {
echo "<b>Oops! we have an issu </b>";
}
?>
You have an else after your if (isset($_POST['Update'])). Inside that else you are displaying errors as if the user tried to submit the form. $_POST['Update'] will only be set if the user tried to submit the form. Move that else inside your if:
if (isset($_POST['Update'])) {
/* a bunch of code to insert into the DB */
// if inserted echo the following messges
if ($r) {
echo "<script> alert('Saved')</script>";
}else{
echo "<b>Oops! we have an issu </b>";
}
}
In Addition:
The commenter is right. You are at risk for SQL Injection. Please use prepared statements instead.
The problem is your else statement is running every time the variable $_POST['Update'] is not set.
One way to fix this is to move your error message inside your form checking code. Something like this would work:
if (isset($_POST['Update'])) {
/* unchanged code snipped */
if ($r) {
echo "<script> alert('Saved')</script>";
} else {
echo "<b>Oops! we have an issu </b>";
}
}
Hope that helps!

Passing variables from page to page

I am trying to pass a variable from one page to another using $_GET, and I can't seem to get it to work. I would appreciate any help.
First I create a link based on the results from the database here.
clients.php
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host={$config->dbhost};dbname={$config->dbname}", $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$uid = $auth->SessionUID($_COOKIE['authID']);
$query = $dbh->prepare("SELECT fname, lname, id FROM client WHERE uid=? ORDER by id");
$query->execute(array($uid));
$rslt = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($rslt as $row ){
echo "<a href=../pages/status.php?id=$row[id]>$row[fname]<br></a>";
}
The result from the link are listed on this page
status.php
$cid = $_GET['id'];
$query = $dbh->prepare("SELECT function FROM funcbathing WHERE cid=?");
$query->execute(array($cid));
$rslt = $query->fetch(PDO::FETCH_ASSOC);
if (empty($rslt)){
header('Location: ../views/careplan.php');
echo $cid
}
else{
header('Location: ../views/home.php');
}
I would like to pass the $cid to this page in a text box, but I can't seem to get it work. Here's the page that the id should get passed to.
careplan.php this is a bigger form but I removed the irrelevant information for simplicity.
<input type="text" name="clientid" value="<?php if(isset($_GET['cid'])) { echo $_GET['cid']; } ?>" />
header('Location: ../views/careplan.php?cid='.$cid);
EDIT:
You should learn to print the strings in a valid manor, check error_reporting(E_ALL); and display_errors=on with your string.
then try this:
echo ''.$row["fname"].'<br>';
or:
echo sprintf('%s<br>', $row['id'], $row['fname']);
or even:
echo "{$row["fname"]}<br>";
or any of the other hundreds way to write a valid string

the user exists in the database into the Get_Id

This is how I'm going to make a small sign system, it is such that it must find out if username is in the Get_id that you have visited,
GET_Id it is the page ID as it is for example 1 or 10
tilmeldt_navn the user's name on the page.
tilmeldt_email the person's own email.
I think like here in this still:
if ($stmt = $mysqli->prepare('SELECT tilmeldt_navn, tilmeldt_email FROM `tilmeldtOpgave` WHERE `get_id` = ?')) {
$stmt->bind_param('i', $id);
$id = $_GET['id'];
$stmt->execute();
$stmt->bind_result($tilmeldt_navn, $tilmeldt_email);
while ($stmt->fetch()) {
if($tilmeldt_navn == "")
{
echo "finds in the database";
}
else
{
echo "The finds in the database so can not sign me again!";
}
}
$stmt->close();
}
the problem is: it does not appear in the with some of them at all.
The need to find out whether the user has signed up for the get_id and if it has it must take the last of if and when it does not have to be the roof the first in the if
Honestly, it's really hard to understand what you really want to happen. But, since you try to
echo "finds in the database" it seems that you want to check if the record exist from your database.
Just try this:
if(isset($_GET['id'])){
$stmt = $mysqli->prepare("SELECT tilmeldt_navn, tilmeldt_email FROM `tilmeldtOpgave` WHERE `get_id` = ?");
$id= $_GET['id'];
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_result();
if($stmt->num_rows == 1) //Check if value is returned
{
while($stmt->fetch()) //To fetch the contents of the row
{
echo 'Result Found';
}
}
else {
echo 'No result found';
}
$stmt->close();
$stmt->free_result();
}
$mysqli->close();
?>
Hope this helps.

Categories