Get user info with name or UserID from Mysql/PHP - php

Can I know what's mistake in here?
I have two tables in my database.
it is this
I have written the code as search player thing. I'll put the name or userid in the form and it'll process the information of user.
Here is my code
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" />
<input type="submit" value="Submit" />
</form>
<?php
include('config.php');
if (!empty($_REQUEST['term']))
{
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = " select u.* from users u inner join ranks r ON (u.UserID = r.UserID) where u.UserID = '%" . $term . "%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query))
{
echo 'Name: ' . $row['Name'];
echo '<br /> Cash: ' . $row['Cash'];
echo '<br /> Score: ' . $row['Score'];
echo '<br /> Race: ' . $row['Race'];
echo '<br /> Horseshoe: ' . $row['Horseshoe'];
}
}
?>
</body>
</html>

First of all you should update your config.php to mysqli_ functions.
and the mysqli_real_escape_string() and mysqli_query() functions need 2 Parameters. First $conn, second: the variable
finally your code should look like this:
<html lang="en">
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<form method="POST">
Search: <input title="searchfield" required type="text" name="term"/>
<input type="submit" name="submit" value="Submit"/>
</form>
<?php
include('config.php');
if (isset($_POST["submit"]) && !empty($_POST["submit"])) {
$term = mysqli_real_escape_string($conn, $_REQUEST["term"]); //make sure the $conn isset
$sql = "SELECT u.* FROM users u INNER JOIN ranks r ON (u.UserID = r.UserID) WHERE u.UserID LIKE '%" . $term . "%'"; // change = to LIKE
$r_query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($r_query)) {
echo 'Name: ' . $row['Name'];
echo '<br /> Cash: ' . $row['Cash'];
echo '<br /> Score: ' . $row['Score'];
echo '<br /> Race: ' . $row['Race'];
echo '<br /> Horseshoe: ' . $row['Horseshoe'];
}
}
?>
</body>
</html>
your config.php should look like this:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "idkw0t";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

you should use like in query as follows
$sql = " select u.* from users u inner join ranks r ON (u.UserID = r.UserID) where u.UserID like '%" . $term . "%'";

Related

Update table in database using mysql/php when profile is edited by user

I am using local phpmyadmin as my database(MYSQL), I am doing something like this and i have no idea why this code is not updating the table in database. I am able to fetch data from database and show it on required page and place.
<?php
session_start();
require('db.php');
$id = session_id();
$query = "SELECT * from new_record where id='" . $id . "'";
$result = mysqli_query($con, $query) or die (mysqli_error());
$row = mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Update Record</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<div class="form">
<h1>Update Record</h1>
<?php
$status = "";
if (isset($_POST['new']) && $_POST['new'] == 1)
{
$id = session_id();
$name = $_POST['name'];
$age = $_POST['age'];
$submittedby = $_SESSION['username'];
$update = "UPDATE new_record SET name='" . $name . "', age='" . $age . "', submittedby='" . $submittedby . "' WHERE id='" . $id . "'";
mysqli_query($con, $update) or die(mysqli_error());
$status = "Record Updated Successfully. </br></br><a href='personal-profile.php'>View Updated Record</a>";
echo '<p style="color:#FF0000;">' . $status . '</p>';
}else {
?>
<div>
<form name="form" method="post" action="">
<input type="hidden" name="new" value="1"/>
<input name="id" type="hidden" value="<?php echo $row['id']; ?>"/>
<p><input type="text" name="name" placeholder="Enter Name" required value="<?php echo $row['name']; ?>"/></p>
<p><input type="text" name="age" placeholder="Enter Age" required value="<?php echo $row['age']; ?>"/></p>
<p><input name="submit" type="submit" value="Update"/></p>
</form>
<?php } ?>
</div>
</div>
</body>
</html>
As mentioned in comments - take care of Injection issues.
session_id() taken into your $id does not have rows in your table. There are no rows in your table matching the MySQL Column id to the current session_id(). You will still have your form displayed with no values for name and age. When you fill and submit, it need to update an existing row which is not available in your table.

Search facility results PhP

Ok so the problem is very simple, basically when you put for example "W" it should output hotel names and guest's surnames that contain that character. It doesn't that hotel names however it never gives me an output for guest's no matter what I put. There are several matching for guest's that should appear however I get nothing. I can't see any mistakes with my code... Help.
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="navigation">
<form action="index.php" method="get">
<input type="submit" name="mainpage" value="Main Page" class="submitbut" id="but1" />
</form>
</div>
<form action="index.php" method="post">
<input type="text" name="search" id="searching" />
<input type="submit" name="data_submit" value="Search" id="scan" />
</form>
<?php
if( isset( $_GET['mainpage'] ) ) exit( header( "Location: mainpage.php" ) );
if ( isset( $_POST["data_submit"] ) ){
$search_term = strip_tags( trim( $_POST['search'] ) );
$conn = new PDO( 'mysql:host=localhost;dbname=u1358595', 'root' );
$stmt = $conn->prepare("SELECT * FROM `hotel` h
INNER JOIN `booking` b ON h.`hotel_id`=b.`hotel_id`
INNER JOIN `guest` g ON g.`guest_id`=b.`guest_id`
WHERE `name` LIKE :search_term;");
$stmt->bindValue(':search_term','%' . $search_term . '%');
$stmt->execute();
echo "
<table>
<tr>
<th>Hotels Matched</th>
</tr>";
while($hotel = $stmt->fetch()) {
echo "
<tr>
<td><a href='details.php?name=".$hotel['name']."'>".$hotel['name']."</a></td>
</tr>";
}
echo "</table>";
$stmt = $conn->prepare("SELECT * FROM `guest` g
INNER JOIN `booking` b ON g.`guest_id`=b.`guest_id`
INNER JOIN hotel ON b.`hotel_id`=h.`hotel_id`
WHERE g.`last_name` LIKE :search_term;");
$stmt->bindValue(':search_term', '%' . $search_term . '%');
$stmt->execute();
echo "
<table>
<tr>
<th>Guests Matched</th>
</tr>";
while($hotel = $stmt->fetch()) {
echo "
<tr>
<td><a href='details.php?name=".$hotel['first_name']."'>".$hotel['last_name']."</a></td>
</tr>";
}
echo "</table>";
$conn = NULL;
}
?>
</body>
</html>
With PDO Prepared statements with LIKE prepare FULL literal first.See PDO Wiki
ie.
$name = "%$name%";
I have simplified your code using one query. I have tested it on 2 tables, you will need to JOIN other table
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" id="searching" />
<input type="submit" name="data_submit" value="Search" id="scan" />
</form>
<?php
$host= "localhost";
$username="XXXX";
$password="XXXX";
$database="XXXX";
function writeTable($host,$database, $username, $password,$search_term) {
//Create query
$sql = "SELECT hotel.name AS hotel, guest.name AS guest
FROM `hotel`
LEFT JOIN `guest` ON hotel.guest = guest.id
WHERE hotel.name LIKE ?
OR guest.name LIKE ?
";
$html = '<table cellpadding="1" cellspacing="1">'. "\n";
//array for column names
$columnNames = array("hotel","guest");
//table header
$html .= '<tr>';
foreach ($columnNames as $value){
$html .= '<th>' . $value . '</th>';
}
$html .= '</tr>'. "\n";
// connect to the database
$db = new PDO("mysql:host=$host;dbname=$database", $hotelname, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Prepare and execute query
$stmt = $db->prepare($sql);
$stmt->execute(array($search_term,$search_term));
// setting the fetch mode
$stmt->setFetchMode(PDO::FETCH_ASSOC);
//Add content
while($row = $stmt->fetch()) {
$html .= '<tr>';
$html .= '<td>' . $row['hotel'] . '</td>';
$html .= '<td>' . $row['guest'] . '</td>';
$html .= '</tr>'. "\n";
}
$html .= '</table>';
echo $html;
// close the connection
$dbh = null;
}
$search = strip_tags(trim($_POST['search'] ) );
if(isset($search) ){
if ($search != ''){
$search_term = '%'.$search.'%';
}else{
$search_term ='';
}
}
writeTable($host,$database, $hotelname, $password,$search_term);
?>
You should be able to modify to suit.

undefined index using update statement

Im trying to update a field in my database by adding to the original number value that is already in there.
i have a system where staff are able to log in and update a the balance of a normal user. Currently i have a test user and staff. the users balance is set to 100. i have the following code:
<?php
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$result = $mysqli->query( "SELECT * FROM Users WHERE Username ='$searchq'");
if ($result){
//fetch result set as object and output HTML
if($obj = $result->fetch_object())
{
echo '<div class="booksearched">';
echo '<form method="POST" id = "books" action="">';
echo '<div class="book-content"><h3>Student Username: '.$obj->Username.'</h3>';
echo '<br>';
echo '<div class="book-content"><i>First Name: <b>'.$obj->FirstName.'</b></i></div>';
echo '<div class="book-desc"><i>Last Name:<b> '.$obj->LastName.'</b></i></div>';
echo '<br>';
echo '<div class="book-qty"> Current Balance<b> '.$obj->Balance.'</b></div>';
echo 'New Balance: <input type="number" name="newBalance" value = "1" min = "1" />';
echo '<br><br>';
echo '<button name="submit_btn" class="save_order">Top Up</button>';
echo '</div>';
echo '</form>';
echo '</div>';
}
}
}
$newBalance="";
$newBalance = $_POST['newBalance'];
if(isset($_POST['submit_btn']) ){
$upsql = "UPDATE users SET Balance = Balance + '$newBalance' WHERE Username='" . $obj->Username . "'";
$stmt = $mysqli->prepare($upsql);
$stmt->execute();
}
?>
Ive tried a few things however i kept getting an error saying:
( ! ) Notice: Undefined index: newBalance
Im not sure what ive done wrong.
Any idea how to fix it?
Edit: Full code
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<br>
<div id="books-wrapper">
<!-- #content to center the menu -->
<div id="content">
<!-- This is the actual menu -->
<ul id="darkmenu">
<li>Home</li>
<li>New Books</li>
<li>Search</li>
<li>Update Balance</li>
</ul>
</div>
<div id = "welcome" >
Welcome, <?=$_SESSION['Username'];?>! <br> Logout
</div>
<br><br>
<h1 id = "mainHeader" >Update a Students Balance</h1>
<br>
<div id = "balanceupdate">
<form id = "adsearch" action="updateBalance.php" method="post">
<input type="text" name ="search" placeholder="Search For a Student">
<button name="submit" value="search">Search</button>
</form>
<br>
</div>
<?php
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$result = $mysqli->query( "SELECT * FROM Users WHERE Username ='$searchq'");
if ($result){
//fetch result set as object and output HTML
if($obj = $result->fetch_object())
{
echo '<div class="booksearched">';
echo '<form method="POST" id = "books" action="">';
echo '<div class="book-content"><h3>Student Username: '.$obj->Username.'</h3>';
echo '<br>';
echo '<div class="book-content"><i>First Name: <b>'.$obj->FirstName.'</b></i></div>';
echo '<div class="book-desc"><i>Last Name:<b> '.$obj->LastName.'</b></i></div>';
echo '<br>';
echo '<div class="book-qty"> Current Balance<b> '.$obj->Balance.'</b></div>';
echo 'New Balance: <input type="number" name="newBalance" value = "1" min = "1" />';
echo '<br><br>';
echo '<button name="submit_btn" class="save_order">Top Up</button>';
echo '</div>';
echo '</form>';
echo '</div>';
}
}
}
$newBalance="";
if(isset($_POST['submit_btn']) && !empty($_POST['newBalance']) ){
$newBalance = $_POST['newBalance'];
$upsql = "UPDATE users SET Balance = Balance + '$newBalance' WHERE Username='" . $obj->Username . "'";
$stmt = $mysqli->prepare($upsql);
$stmt->execute();
}
?>
</body>
</html>
It's throwing that notice because you need to place $newBalance = $_POST['newBalance']; inside if(isset($_POST['submit_btn'])){...} and verify that it is not empty (or set).
$newBalance="";
if(isset($_POST['submit_btn']) && !empty($_POST['newBalance']) ){
$newBalance = $_POST['newBalance'];
$upsql = "UPDATE users SET Balance = Balance + '$newBalance'
WHERE Username='" . $obj->Username . "'";
$stmt = $mysqli->prepare($upsql);
$stmt->execute();
}
You can also use isset($_POST['newBalance']) instead of !empty($_POST['newBalance'])
Sidenote: You may want to add a submit type for your button.
echo '<button type="submit" name="submit_btn" class="save_order">Top Up</button>';
Yet, it may not be required; do try it if you're still experiencing problems.
Edit:
Under
echo '<div class="book-content"><h3>Student Username: '.$obj->Username.'</h3>';
add
echo '<input type="hidden" name="username" value = "'.$obj->Username.'" />';
then under
$newBalance = $_POST['newBalance'];
add
$username = $_POST['username'];
and modify your query to read as
$upsql = "UPDATE users SET Balance = Balance + '$newBalance'
WHERE Username='".$username ."'";
My quoting may be a bit off for
echo '<input type="hidden" name="username" value = "'.$obj->Username.'" />';
where you may have to change it to
echo '<input type="hidden" name="username" value = '".$obj->Username."' />';
Edit #2:
Another way to do this since you're already using sessions <?=$_SESSION['Username'];?> would be to assign a variable to it and pass it in your query.
$username = $_SESSION['Username'];
$upsql = "UPDATE users SET Balance = Balance + '$newBalance'
WHERE Username='".$username ."'";
Edit #3:
Where you have
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
replace it with
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$student = $_POST['search'];
$_SESSION['student'] = $student;
echo $_SESSION['student']; // see what echos here
then in your query, do:
$upsql = "UPDATE users SET Balance = Balance + '$newBalance'
WHERE Username='".$student ."'";
If that doesn't work, I don't know what else to do that will be of further help. My tests were conclusive and worked. Your query may be failing, I have no more ideas at this point.
Base yourself on this scenario:
$_POST['search'] = "student1";
$student = $_POST['search'];
$_SESSION['student'] = $student;
// echo $_SESSION['student'];
$student2 = $student;
echo $student2; // will echo student1

Turning a mysql column into an array and using the array in a dropdown

Long time listener, first time caller. I'm having trouble with pulling a column called "Rep_IP" from a mysql table called "roster", turning it into an array, and then using that array to populate a dropdown in html. I've tried several suggestions listed here as well as other places and I'm not having any luck. The page shows up just fine but the dropdown has no options to select. I figured I would see if one of you could tell me what I am doing wrong here.
<html>
<body>
<form action="insert.php" method="post">
<p>Rep ID:</p>
<?php
$con = mysql_connect("localhost", "root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("rep_stats", $con);
$query = "SELECT Rep_ID FROM roster";
$result = mysql_query($query) or die ("no query");
$result_array = array();
echo "$query"
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
?>
<select name="Rep_ID">
<?php
foreach($result_array as $rep)
{
echo "<option value=" . $rep['Rep_ID'] . ">" . $rep['Rep_ID'] . "</option>";
}
?>
</select>
Issues Handled: <input type="number" name="IssuesHandled">
Hours Worked: <input type="number" step="any" name="HoursWorked">
<input type="submit">
</form>
</body>
</html>
As you can see, the drop down is part of a form that is used to create an entry in a new table as well. I don't know if that makes a difference but I figured I would point it out.
Try this.
<select name="Rep_ID">
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<option value=" . $row['Rep_ID'] . ">" . $row['Rep_ID'] . "</option>";
}
?>
</select>
Try this:
<?php
function select_list(){
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link)
{
echo ('Could not connect');
}
ELSE {
$query = "SELECT Rep_ID FROM roster";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<option value=" . $row['Rep_ID'] . ">" . $row['Rep_ID'] . "</option>";
}
}
mysqli_close($link);
}
$begin_form =
<<< EODBEGINFORM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Insert data </title></head>
<body>
<form action="insert.php" method="post" name="form1">
<p>Rep ID:</p>
<select name="reps" form="form1">
EODBEGINFORM;
$end_form =
<<< EODENDFORM
</select><br>
Issues Handled: <input type="text" size="12" name="IssuesHandled"><br>
Hours Worked: <input type="text" size="12" name="HoursWorked"><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
EODENDFORM;
echo $begin_form;
echo select_list();
echo $end_form;
?>
You will notice that I have used MYSQLI_ istead of MYSQL_ the reason is that this better for new code, see the comments above.
I debugged your code and ran I to a lot of problems.:-( The main problem was:
echo "$query" Your forgot the semicolon at the end of the line.
Good luck with you project.

Troubleshooting HTML and PHP / MySQL

Long time reader, first time poster. I am a novice PHP enthusiast, and I have a page that I have been working. Right now I have the DB connection working well and my SELECT statement is giving me the info needed. My problems are two fold (maybe more after this post; set your phasers to cringe):
At one point, I had the INSERT working, but it suddenly stopped and no amount of tweaking seems to bring it back. I have verified that the INSERT statement works in a seperate PHP file without variables.
When I did have the INSERT working, every refresh of the page would duplicate the last entry. I have tried tried several ways to clear out the $_POST array, but I think some of my experimenting lead back to problem #1.
<?php
$dbhost = "REDACTED";
$dbuser = "REDACTED";
$dbpass = "REDACTED";
$dbname = "guest_list";
// Create a database connection
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("DB's not here, man: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
// replacement for mysql_real_escape_string()
function html_escape($html_escape) {
$html_escape = htmlspecialchars($html_escape, ENT_QUOTES | ENT_HTML5, 'UTF-8');
return $html_escape;
}
// Posting new data into the DB
if (isset($_POST['submit'])) {
$first = html_escape($_POST['first']);
$last = html_escape($_POST['last']);
$contact = html_escape($_POST['contact']);
$associate = html_escape($_POST['associate']);
$insert = "INSERT INTO g_list (";
$insert .= "g_fname, g_lname, g_phone, g_association) ";
$insert .= "VALUES ('{$first}', '{$last}', '{$contact}', '{$associate}')";
$insert .= "LIMIT 1";
$i_result = mysqli_query($connection, $insert);
// I have verified that the above works by setting the varialble
// in the VALUES area to strings and seeing it update
}
$query = "SELECT * ";
$query .= "FROM g_list ";
$query .= "ORDER BY g_id DESC";
$q_result = mysqli_query($connection, $query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Guest List</title>
<link href="guest.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<header>
<h1>REDACTED</h1>
<h2>Guest Registry</h2>
</header>
<div class="container">
<div class="registry">
<form name="formup" id="main_form" method="post">
<fieldset>
<legend>Please enter your name into the registry</legend>
<p class="first">First Name:
<input type="text" name="first" value="" placeholder="One or more first names" size="64"></p>
<p class="last">Last Name:
<input type="text" name="last" value="" placeholder="Last name" size="64"></p>
<p class="contact">Phone Number or Email:
<input type="text" name="contact" value="" placeholder="" size="32"></p>
<p class="associate">Your relation?
<input type="text" name="associate" value="" placeholder="" size="128"></p>
<p class="submit">
<input type="submit" name="submit" title="add" value="submit" placeholder=""></p>
</fieldset>
</form>
</div>
</div>
<h3>Guest List:</h3>
<table>
<tr>
<th>Firstname(s)</th><th>Lastname</th>
<th>Phone or Email</th><th>Association</th>
</tr>
<?php while($guest = mysqli_fetch_assoc($q_result)) {
echo "<tr>" . "<td>" . $guest["g_fname"] . "</td>"
. "<td>" . $guest["g_lname"] . "</td>"
. "<td>" . $guest["g_phone"] . "</td>"
. "<td>" . $guest["g_association"] . "</td>" . "</tr>";
} ?>
</table>
<footer>
<div>Copyright <?php echo date("Y"); ?>, REDACTED, LLC.</div>
<?php
if (isset($connection)) {
mysqli_close($connection);
}
?>
</footer>
</body>
</html>
These two lines will fail:
$insert .= "VALUES ('{$first}', '{$last}', '{$contact}', '{$associate}')";
$insert .= "LIMIT 1";
Two problems here, all with the second line:
No SPACE between ) and LIMIT: )LIMIT 1 is your code;
LIMIT 1 in an INSERT is not allowed....

Categories