So i've got this input where i can put a username in and it'll use $_POST to get what i put in the input box however i'm struggling on how to get all the information from my database relating to this username and displaying it?
<form action="ProcessPlayerSearch.php" method="POST">
<div class="input-group input-group-sm">
<input type="text" name="SearchUser" id="SearchUser" class="form-control">
<span class="input-group-btn">
<button type="submit" class="btn btn-info btn-flat" type="button">Search</button>
</span>
</div>
</h4>
</form>
This is my ProcessPlayerSearch.php
function GetPlayerSearch(){
global $database;
$user = $_POST['Searchuser'];
$q = "SELECT * FROM NEWPlayerInfo WHERE player=$user";
$result = $database->query($q);
/* Error occurred, return given name by default */
$num_rows = mysqli_num_rows($result);
if(!$result || ($num_rows < 0)){
echo "User not found";
return;
}
if($num_rows == 0){
echo "User not found";
return;
}
for($i=0; $i<$num_rows; $i++){
mysqli_data_seek($result, $i);
$row=mysqli_fetch_row($result);
$uuid = $row[0]; //UUID
$player = $row[1]; //player
$kicks = $row[2]; //kicks
$bans = $row[3]; //bans
echo "$uuid<br>";
echo "$player<br>";
echo "$kicks<br>";
echo "$bans<br>";
}
}
and the error i get is
mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in
however i don't get why it would return a boolean? as i've entered a string into the input? Any help thanks.
Since you are displaying a single user data, Using for loop would be a little overhead. Now we return the array containing the user info from your function:
function GetPlayerSearch($user){
global $database;
$user = $_POST['Searchuser'];
$q = "SELECT * FROM `NEWPlayerInfo` WHERE player='$user'";
$result = $database->query($q);
/* Error occurred, return given name by default */
$num_rows = mysqli_num_rows($result);
$res =mysqli_fetch_assoc($result);
$userinfo =array();
if($num_rows>1){
$userinfo[] = $res;
}else{
$userinfo[] = array();
}
return $userinfo;
}
Now search the user:
if(isset($_POST['SearchUser'])){
$user = isset($_POST['SearchUser'])? $_POST['SearchUser']:'';
$player = GetPlayerSearch($user);
}
Display a single player data:
if(!empty($player)){ //you can also use array_filter()
echo $player['UUID'].'<br>';
echo $player['player'].'<br>';
echo $player['kicks'].'<br>';
}else{
echo 'No user';
}
Related
I need to echo a download button if there are certain correct results, but when I echo the download button it decides to echo more than 1. How do I correct this?
heres my code:
<?php
$u = $_SESSION["username"];
$getscripts = $conn->prepare("SELECT * FROM project_sa");
$getscripts->execute();
while ($row = $getscripts->fetch(PDO::FETCH_BOTH)) {
$sec = $conn->query('SELECT * FROM us WHERE username="wafflezzz"');
$sec->execute();
while ($rowx = $sec->fetch(PDO::FETCH_BOTH)) {
$checker = $rowx[$row["script_title"]];
if ($checker == $row["script_title"]) {
$geturl = $conn->prepare("SELECT * FROM project_sa WHERE script_title='$checker'");
$geturl->execute();
while ($row = $geturl->fetch(PDO::FETCH_BOTH)) {
echo '
<form method="post" action="dl.php">
<input name="bname" value="<?php echo $branded_m_img_url; ?>" hidden></input>
<input type="submit" class="ui huge button" value="Download"></input>
</form>';
}
}
}
}
?>
It returns about 2 broken duplicate entries when there is only 1 entry in the database!
"You have nested while loops, that's why you get duplicate entries, you also overwrite $row in the inner while loop – Alon Eitan yesterday"
After I fixed that, it worked!
this is my login.php file
<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
Name : <input type="text" name="name"><br/>
Password : <input type = "text" name="password"><br/>
<input type="submit" name="login" value="Log In">
</form>
<?php
$name=$password="" ;
if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
$name = testInput($_POST["name"]);
$password = testInput($_POST["password"]);
}//if ends here
//testInput function
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}//testInput ends here
if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){
//echo "Name ".$_POST["name"];
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")){
if($result->num_rows > 1){
echo "you are logged in";
while ($row = $result->fetch_assoc()){
echo "Name ".$row["name"]."-Password ".$row["password"];
}//while loop ends here
}//if ends here
/* free result set */
$result->close();
}
else{
print "Wrong Credentials "."<br>";
die(mysqli_error($conn));
}
}
//close connection
$conn->close();
?>
</body>
</html>
One problem is that my query
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")) returns column names as one row. I don not know whether it is ok ? The other thing whether I put wrong name or password or correct , in both cases I do not get any output. What I am doing wrong here ? And if you can please tell me how to write a mysqli query in php with correct format with a comprehensive example . I searched on google but there are different ways so I am confused specially when column names and variables come in the query.
Your test_input function is weak/unsafe, also, mysql_query is depricated, use mysqli and prepared statements as explained here: http://php.net/manual/en/mysqli.prepare.php
Furthermore, I included a section of code I use for my login system (bit more sophisticated using salts etc, you should be able to compile it in a piece of script suitable for you.
//get salt for username (also check if username exists)
$stmtfc = $mysqli->stmt_init();
$prep_login_quer = "SELECT salt,hash,lastlogin FROM users WHERE name=? LIMIT 1";
$stmtfc->prepare($prep_login_quer);
$stmtfc->bind_param("s", $username);
$stmtfc->execute() or die("prep_login_quer error: ".$mysqli->error);
$stmtfc->store_result();
if ($stmtfc->num_rows() == 1) {
$stmtfc->bind_result($salt,$hash,$lastlogin);
$stmtfc->fetch(); //get salt
$stmtfc->free_result();
$stmtfc->close();
I don't know what do you mean but thats how i query mysqli
$query = mysqli_query($db, "SELECT * FROM users WHERE name='$name' AND password='$password'");
if($query && mysqli_affected_rows($db) >= 1) { //If query was successfull and it has 1 or more than 1 result
echo 'Query Success!';
//and this is how i fetch rows
while($rows = mysqli_fetch_assoc($query)) {
echo $rows['name'] . '<br />' ;
}
} else {
echo 'Query Failed!';
}
i think thats what you mean
EDIT:
<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
Name : <input type="text" name="name"><br/>
Password : <input type = "text" name="password"><br/>
<input type="submit" name="login" value="Log In">
</form>
<?php
$name = null ;
$password= null ;
if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
$name = mysqli_real_escape_string($conn, $_POST["name"]); //I updated that because your variables are not safe
$password = mysqli_real_escape_string($conn, $_POST["password"]);
}//if ends here
//testInput function
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}//testInput ends here
if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='{$name}' and password='{$password}'")){
print "rows are ".mysqli_num_rows($result)"<br>";//number of rows
if($result && mysqli_affected_rows($conn) >= 1){//If query was successfull and it has 1 or more than 1 result
echo "you are logged in<br>";
while ($row = mysqli_fetch_assoc($result)){
echo "Name ".$row["name"]."-Password ".$row["password"];
}//while loop ends here
}//if ends here
/* free result set */
mysqli_free_result($result);
}
else{
print "Wrong Credentials "."<br>";
die(mysqli_error($conn));
}
}
//close connection
mysqli_close($conn);
?>
</body>
</html>
try to change this query
$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")
to
$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password' limit 1")
then you will get only one row , and try to change
$row = $result->fetch_assoc()
to
$row = $result->mysqli_fetch_row()
then you can display the results by colomn number instead of colomn name
<?php
mysql_connect("abc.com","user","password");
mysql_select_db("database name");
$query1="select * from table_name";
$exe1= mysql_query($query1);
$row= mysql_fetch_assoc($exe1);
if($row["email"]==$_POST["email"] && $row["[password"]==$_POST["password"]) {
echo "Login successfully";
} else {
echo "error in login";
}
?>
enter your column name in row["email"] and $row["password"]
I have a PHP website to display products. I need to introduce a 'Search' feature whereby a keyword or phrase can be found among number of products.
I went through number of existing scripts and wrote/modified one for me which though able to connect to database, doesn't return any value. The debug mode throws a warning " mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given ". Seems I am not collecting the query value correctly. The PHP Manuals says that mysqli_query() returns FALSE on failure and for successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object and for other successful queries mysqli_query() will return TRUE ".
Any suggestions?
<form name="search" method="post" action="search.php">
<input type="text" name="searchterm" />
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="Search" />
</form>
<?php
$searchterm=trim($_POST['searchterm']);
$searching = $_POST['searching'];
$search = $_POST['search'];
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo 'Results';
//If they forget to enter a search term display an error
if (!$searchterm)
{
echo 'You forgot to enter a search term';
exit;
}
//Filter the user input
if (!get_magic_quotes_gpc())
$searchterm = addslashes($searchterm);
// Now connect to Database
# $db = mysqli_connect('localhost','username','password','database' );
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to the database. Please try again later.';
exit;
}
else {
echo "Database connection successful."; //Check to see whether we have connected to database at all!
}
//Query the database
$query = "SELECT * FROM wp_posts WHERE post_title LIKE '%$searchterm%' OR post_excerpt LIKE '%$searchterm%' OR post_content LIKE '%$searchterm%'";
$result = mysqli_query($db, $query);
if (!$result)
echo "No result found";
$num_results = mysqli_num_rows($result);
echo "<p>Number of match found: ".$num_results."</p>";
foreach ($result as $searchResult) {
print_r($searchResult);
}
echo "You searched for $searchterm";
$result->free();
$db->close();
}
To do your literal search as you have it, you would need to change the code '%{searchterm}%' to '%$searchterm%', since the brackets aren't needed and you were searching for the phrase "{searchterm}." Outside of that you might want to take a look at FULLTEXT search capabilities since you're doing a literal search in your current method.
To make the output look like Google's output you would simply code a wrapper for each search result and style them with CSS and HTML.
I think it should be something like '%$searchterm%', not '%{searchterm}%' in your query. You are not searching for your variable $searchterm in your example.
Google's display uses LIMIT in the query so it only displays a certain amount of results at a time (known as pagination).
This is tested and works. You will need to change 1) db connection info in the search engine class. 2) If you want it to be on separate pages, you will have to split it up. If not, copy this whole code to one page and it will work on that one page.
<?php
class DBEngine
{
protected $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
$rows = $query->fetchAll();
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
class SearchEngine
{
protected $searchterm;
public function execute($searchword)
{
$this->searchterm = htmlentities(trim($searchword), ENT_QUOTES);
}
public function display()
{ ?>
<h1>Results</h1>
<?php
//If they forget to enter a search term display an error
if(empty($this->searchterm)) { ?>
<h3>Search Empty</h3>
<p>You must fill out search field.</p>
<?php }
else {
$con = new DBEngine('localhost','database','username','password');
$results = $con->Fetch( "SELECT * FROM wp_posts WHERE post_title LIKE '%".$this->searchterm."%' OR post_excerpt LIKE '%".$this->searchterm."%' OR post_content LIKE '%".$this->searchterm."%'");
if($results !== 0 && !empty($results)) { ?>
<p>Number of match found: <?php echo count($results); ?> on search:<br />
<?php echo strip_tags(html_entity_decode($this->searchterm)); ?></p>
<?php
foreach($results as $rows) {
echo '<pre>';
print_r($rows);
echo '</pre>';
}
}
else { ?>
<h3>No results found.</h3>
<?php
}
}
}
}
if(isset($_POST['submit'])) {
$searcher = new SearchEngine();
$searcher->execute($_POST['searchterm']);
$searcher->display();
} ?>
<form name="search" method="post" action="">
<input type="text" name="searchterm" />
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="Search" />
</form>
The search function works like a charm, but I'm not sure how to add certain "extras" to it. When there are results to display, I would also like it to say:
"Your search returned x results."
Followed by the results.
When there are no results to display, I would like it to say:
"Your search returned no results. Please try again."
And when the user does not input anything into the search form, I would like it to say:
"You did not enter a search term."
I'm a PHP beginner, and I'm not sure how to implement this into my current code; I've tried a bunch of different ways, and it either gives me errors or returns a blank page when there are no results.
Any direction or help would be great. Thank you.
Here is my current code:
<?php
//STEP 1 Connect To Database
$connect = mysql_connect("localhost","tarb89_admin","leccums");
if (!$connect)
{
die("MySQL could not connect!");
}
$DB = mysql_select_db('tarb89_characters');
if(!$DB)
{
die("MySQL could not select Database!");
}
//STEP 2 Check Valid Information
if(isset($_GET['search']))
{
//STEP 3 Declair Variables
$Search = $_GET['search'];
$result = mysql_query("SELECT * FROM characters WHERE name LIKE '%$Search%' ");
while($row = mysql_fetch_assoc($result))
{
$name = $row['name'];
$id = $row['id'];
$breed = $row['breed'];
$gender = $row['gender'];
$genetics = $row['genetics'];
$profile = $row['profile'];
$player = $row['player'];
$color = $row['color'];
$markings = $row['markings'];
$traits = $row['traits'];
$defects = $row['defects'];
$extras = $row['extras'];
echo " <h3>$name</h3>
<table width='700px' cellpadding='5' cellspacing='0'>
<tr>
<td><p>
<b>ID Number: </b>$id<br>
<b>Breed: </b>$breed<br>
<b>Gender: </b>$gender<br>
<b>Genetics: </b>$genetics<br>
<b>Profile:</b> <a href='$profile'>$profile</a><br>
<b>Player:</b> $player</p></td>
<td><p>
<b>Color:</b> $color<br>
<b>Markings:</b> $markings<br>
<b>Traits:</b> $traits<br>
<b>Defects:</b> $defects<br>
<b>Extras:</b> $extras</p></td>
</table>";
}
}
?>
Use mysql_num_rows() to return number of rows
if($search!="") {
// Your Query
$num = mysql_num_rows($result);
if($num >= 1)
{
echo "Your search returned $num results";
// your code
}
else
{
echo "Your search returned no results. Please try again";
}
} else {
echo "You did not enter a search term";
}
YOUR CODE
if(isset($_GET['search']))
{
//STEP 3 Declair Variables
$Search = $_GET['search'];
$result = mysql_query("SELECT * FROM characters WHERE name LIKE '%$Search%' ");
$num = mysql_num_rows($result);
if($num >= 1)
{
echo "Your search returned $num results";
while($row = mysql_fetch_assoc($result))
{
$name = $row['name'];
$id = $row['id'];
$breed = $row['breed'];
$gender = $row['gender'];
$genetics = $row['genetics'];
$profile = $row['profile'];
$player = $row['player'];
$color = $row['color'];
$markings = $row['markings'];
$traits = $row['traits'];
$defects = $row['defects'];
$extras = $row['extras'];
echo " <h3>$name</h3>
<table width='700px' cellpadding='5' cellspacing='0'>
<tr>
<td><p>
<b>ID Number: </b>$id<br>
<b>Breed: </b>$breed<br>
<b>Gender: </b>$gender<br>
<b>Genetics: </b>$genetics<br>
<b>Profile:</b> <a href='$profile'>$profile</a><br>
<b>Player:</b> $player</p></td>
<td><p>
<b>Color:</b> $color<br>
<b>Markings:</b> $markings<br>
<b>Traits:</b> $traits<br>
<b>Defects:</b> $defects<br>
<b>Extras:</b> $extras</p></td>
</table>";
}
}
else
{
echo "Your search returned no results. Please try again";
}
} else {
echo "You did not enter a search term";
}
Note: mysql_* functions are deprecated, Move on mysqli_* functions asap
I have a html page with the form log-in with username and password. When people enter the correct password, it will take them to the php page with their bills. If the password is incorrect, it will display the error message and then exit the program. I got the log-in function to work. However, it's also effecting my other program. Now every time i try to write something in the item/amount row, it also display the error message and exit the program. I know it has something to do with the $numresult>0 condition. When i took that condition out, my amount/item rows work, but the log-in page also allow blank entry in username/password to log in. Any idea how i can make sure that people have to enter the correct password (not a blank entries) to log in, at the same time, get my item/amount rows in the second page behave as normal? My codes are below. Sorry it's a little long.
</head>
<body style="font-family: Arial, Helvetica, sans-serif; color: black;" onload=>
<h1>My Bills</h1>
<form method=post>
<?php
//*************************************************
//Connect to Database
//*************************************************
//*************************************************
//Verify password and username
//*************************************************
$password = $_POST['password']; //retrieve variables for password and userId
$userid = $_POST['userid'];
$query = "SELECT * FROM valid_logon WHERE userid = '$userid' AND
password='$password'"; //get query from database
$result = mysql_query($query);
$numresults = mysql_num_rows($result); //get row number
$row = mysql_fetch_array($result); //get array into variable
$dbuserid = $row['userid'];
$dbpassword = $row['password'];
if ($numresults>0)
{
if ($userid == $dbuserid && $password == $dbpassword)
{
process();
}
}else{
err_msg();
}
//*************************************************
//Error message.
//*************************************************
function err_msg()
{
print "The username and/or password you have entered are invalid.";
print "</body>";
print"</html>";
exit;
}
//*************************************************
//Write out records with data if they exist.
//*************************************************
function process()
{
print "<table>";
print "<tr><th>Item</th><th>Amount</th></tr>";
$action = $_POST['action'];
if ($action == 'update')
{
$write_ctr = 1;
// Delete all rows in the table
$query = "DELETE FROM n1417_expenses ";
$result = mysql_query($query);
if (mysql_error()) {
echo("<br>MySQL Error - Cannot delete from table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
// Loop through table and insert values into the database
while (true)
{
$item_name = 'item'."$write_ctr";
$item_value = $_POST[$item_name];
$amount_name = 'amount'."$write_ctr";
$amount_value = $_POST[$amount_name];
if (empty($item_value))
{
break;
}
// Insert an item to the table
if(!is_numeric($amount_value))
{
print "<font color=red>I'm sorry, amount \"".$amount_value."\" is not a valid number.</font><br>\n";
}else{
$query = "INSERT INTO n1417_expenses (item, amount)
VALUES('".$item_value."','".$amount_value."') ";
$result = mysql_query($query);
}
if (mysql_error())
{
echo("<br>MySQL Error - Cannot insert a row into table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
$write_ctr++;
}
}
//*************************************************
//Now Select from table and Display
//*************************************************
$err_cnt = 0;
$read_ctr = 1;
$query = "SELECT item, amount FROM n1417_expenses ";
$result = mysql_query($query);
if (mysql_error()) {
echo("<br>MySQL Error- Cannot select from table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
if (!empty($result))
{
$rowresults = mysql_num_rows($result);
if ($rowresults > 0)
{
for ($read_ctr=1; $read_ctr<=$rowresults; $read_ctr++)
{
$row = mysql_fetch_array($result);
$item_value = $row['item'];
$item_name = 'item'."$read_ctr";
$amount_value = $row['amount'];
$amount_name = 'amount'."$read_ctr";
print "<tr>";
print "<td><input type=text name=$item_name value='$item_value'></td>\n";
print "<td><input type=text name=$amount_name value='$amount_value'></td>\n";
print "<td>";
print "</tr>";
$total_amt = $total_amt + $amount_value;
}
}
}
//*************************************************
//Now write the blank lines
//*************************************************
for ($i = $read_ctr; $i < $read_ctr + 2; $i++)
{
$item_name = 'item'."$i";
$amount_name = 'amount'."$i";
print '<tr>';
print "<td><input type=text name=$item_name value=''></td>\n";
print "<td><input type=text name=$amount_name value=''></td>\n";
print '</tr>';
}
print "</table>";
print "<br>Total Bills: $total_amt";
}
?>
<br><input type=submit value=Submit>
<br<br>
<!-- Hidden Action Field -->
<input type=hidden name=action value=update>
</form>
To answer the question posted, your problem appears to be that the username and password being are checked again when your user submits the form. Because the fields don't exist, the query finds zero rows, triggering your error message.
There are a number of ways of fixing your problem, one way would be to use a Session to remember that a user is logged in. This could be implemented by altering your password check as follows:
session_start();
if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in'])
{
$password = $_POST['password']; //retrieve variables for password and userId
$userid = $_POST['userid'];
$query = "SELECT * FROM valid_logon WHERE userid = '".mysql_real_escape_string($userid)."' AND
password='".mysql_real_escape_string($password)."'"; //get query from database
$result = mysql_query($query);
$numresults = mysql_num_rows($result); //get row number
$row = mysql_fetch_array($result); //get array into variable
$dbuserid = $row['userid'];
$dbpassword = $row['password'];
if ($numresults>0)
{
if ($userid == $dbuserid && $password == $dbpassword)
{
$_SESSION['logged_in'] = TRUE;
process();
}
}else{
err_msg();
}
}
I've kept the code as similar to the original as possible, but I will echo the comments above on the need to secure your SQL calls. Have a look at using PDO if possible, or at the very least start using mysql_real_escape_string as above.