I'm creating a function to search for users within my database, but does not work correctly throwing the following error, I have a good time trying different methods but I manage to make it work so I recuerro to you hoping that you can help
Fatal error: Call to a member function fetch_array() on null
That is the mistake that pulls me on the page and this is my code
<form method="post">
<input name="usuario" type="text" class="INPUT-GENERAL" placeholder="Buscar usuario">
<button class="BOTON-GENERAL" type="submit">Buscar</button>
</form>
<?php
$Usuario = $_POST['usuario'];
if ($Usuario!="") {
$Busqueda = $MySQLi_CON->query("SELECT * FROM users WHERE username LIKE '".real_escape_string($Usuario)."' ");
}
while ($Resultado = $Busqueda->fetch_array()) {
?>
<?php
echo '<meta http-equiv="Refresh" content="0;URL=./usuarios.php?usuario='.$Resultado['username'].'" />';
?>
<?php } ?>
try this
<?php
$Usuario = real_escape_string($_POST['usuario']);
if (!empty($Usuario)) {$Busqueda = $MySQLi_CON->query("SELECT * FROM users WHERE username LIKE '".$Usuario."' ");
}
if($Busqueda){
while ($Resultado = $Busqueda->fetch_array()) {echo '<meta http-equiv="Refresh" content="0;URL=./usuarios.php?usuario='.$Resultado['username'].'" />';}
}
?>
and avoid msqli connections use pdo next time msqli allmost finish
Related
the registration form is connected to the database via db.php but I am having trouble in submitting the login details.
<html>
<head>
<?php
include('db.php');
$username = #$_POST['username'];
$password = #$_POST['password'];
$submit = #$_POST['submit'];
the main problem is after the submit button is clicked by an existing user it should give the message but there's problem in the if statement, because on the wamp server its showing only the else message i.e. Error.
if ($submit)
{
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
if (mysql_num_rows($result)) {
$check_rows = mysql_fetch_array($result);
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
echo "<center>";
echo "You are now Logged In. ";
echo "</center>";
}
else {
echo "<center>";
echo "No User found. ";
echo "</center>";
}
}
else echo "Error";
?>
</head>
<body>
<form method="post">
Username : <input name="username" placeholder="Enter Username" type="text"><br></br>
Password : <input name="password" placeholder="Enter Password" type="password"><br>
<input type="submit" value="Submit">
</body>
</html>
You want get $_POST with name submit, but do not send it to the form
Try change
<input type="submit" value="Submit">
to
<input type="submit" name="submit" value="Submit">
Firstly this is old style of php/mysql. So look at PDO on php.net seeing as you are setting out on new project it really wont be hard to make the change now rather than later.
Now onto your issue. if you intend on carrying on with your old method try this.
$sql = "SELECT * FROM user WHERE username=' . $username . ' AND password=' . $password . '";
// check the query with the die & mysql_error functions
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_num_rows($query);
// checking here equal to 1 In a live case, for testing you could use >= but not much point.
if ($result == 1) {
// Checking needs to be Assoc Now you can use the field names,
// otherwise $check_rows[0], $check_rows[1] etc etc
$check_rows = mysql_fetch_assoc($query); // oops we all make mistakes, query not result, sorry.
// This is bad but for example il let this by,
// please dont access user supplied data without
// validating/sanitising it.
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
} else {
// do not logged in here
}
The same in PDO
$sql=" Your query here ";
$pdo->query($sql);
$pdo->execute();
$result = $pdo->fetch();
if ($result = 1) {
// do login stuff
} else {
// no login
}
Remember though that you need to set up PDO and it may not be available on your server by default (older php/mysql versions) but your host should be happy enough to set them up.
I have a database driven website that has a login to a member or admin area. The login says, "Welcome, Member, pat#email.com" (for example) and I want it to say - "Welcome, Member, Pat" (for example). I have a function that I know works for this, but for some reason I can't get it to work now. It is giving me this error and saying that results is NULL:
Notice: Undefined variable: results in J:\XAMPP\htdocs\tire\admin\home.php on line 59
Below is the two different get_name functions I've tried - note that I have tried one of these and didn't have any trouble getting it to work before.
function get_name($results) {
$name = preg_split("/#/", $results['email']);
$name = ucfirst($name[0]);
return $name;
}
function get_name($results) {
list($name, $email) = array_pad(explode('#', $results['name'], 2), 2, null);
return $name;
}
And here is the logout form:
<form action="index.php" method="post" id="logoutform.php">
<fieldset>
<legend>Logout</legend>
<?php
echo "Welcome, ";
echo $_SESSION['level']. ", ";
echo $_SESSION['loginName'];
echo get_name($results);
var_dump($results);
?> <br /> <br/> <br/> <br/>
<input type="submit" name="action" value="logout"/>
</fieldset>
</form>
Connect function:
function connect($loginName) {
global $db;
$query = "SELECT email, level, password FROM members WHERE email = '$loginName'";
$result = $db->query($query);
$results = $result->fetch(PDO::FETCH_ASSOC);
return $results;
}
I'm trying at the moment to create a login with PHP and MySQL but I'm stuck. The array that's supposed to give me Data from the database only returns "Null" I used var_dumb().
This is the index.php file :
<?php
include_once './Includes/functions.php';
?>
<!DOCTYPE html
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<form method="POST">
<label>User ID :</label>
<input id="login_username" name="login_username" type="login"><br>
<label>Password :</label>
<input id="login_password" name="login_password" type="password" ><br>
<input id="login_submit" name="login_submit" type="submit">
</form>
</div>
</body>
</html>
This is the function.php file :
<?php
require_once 'dbconnect.php';
function SignIn() {
$lUser = $_POST['login_username'];
$lPassword = md5($_POST['login_password']);
$querySQL = "SELECT * FROM tblUser WHERE dtUser='$lUser' AND dtPassword='$lPassword'";
$queryResult = mysqli_query($dbc, $querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayLogin[] = $row;
}
if ($lUser == $dataArrayLogin['dtUser'] && $lPassword == $dataArrayLogin['dtPassword']) {
echo $dataArrayLogin;
$popup = "Login Succeed";
echo "<script type='text/javascript'>alert('$popup');</script>";
$_SESSION['user'] = $lUser;
header("Location: ./british.php");
} else {
echo $dataArrayLogin;
$popup = "Login Failed";
echo "<script type='text/javascript'>alert('$popup');</script>";
}
}
if (isset($_POST['login_submit'])) {
SignIn();
}
?>
Could you help me out ?
This could be, because you have no results?
Anyway, I've checked your code, and it's not good, because you are try to use this:
$dataArrayLogin['dtUser']
There is no 'dtUser' key in your $dataArrayLogin.
When you fetching the row, you are put it into a while cycle, and collect the data into an array:
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayLogin[] = $row;
}
Remove the while cycle. Simple use:
$dataArrayLogin = mysqli_fetch_assoc($queryResult);
And if you echo an array, the result will be Array. Use var_dump instead.
in your html form, you don't have <form method="POST" action="SignIn">. so when you submit the form, its not going somewhere.
You need to start debugging your script. Below are the steps I would take:
Do a var_dump() on the $_POST to see if it contains all values you want
echo the $querySQL to see if all values are put in correctly
Check your database if it actually contains the record with which you are trying to login
Fetch mysql errors using mysqli_error();
That should bring your error to light.
Edit:
I often find it usefull to place some echos throughout my script to find out what parts of the code are being accessed and what parts are being skipped.
I would add a LIMIT 1 to your query as there should only be one user with the entered credentials. This way you'll also be able to skip the while loop.
Change query like this
$querySQL = "SELECT * FROM tblUser WHERE dtUser=' ".$lUser." ' AND dtPassword=' ".$lPassword." ' ";
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>
I'm making a login page for the admins to make some changes to a website easily. However, the login page isn't working correctly. It won't go to the error page InvalidLogin.html and it won't go to the next page of the admin website AdminChanges.php.
Instead, I'm getting the following message:
Not Found
The requested URL /website/method="post" was not found on this server.
<?php
if ($_POST['submit'] == "submit")
{
$userName = $_POST['username'];
$passWord = $_POST['password'];
$db= mysql_connect("localhost", "root", "root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("onlineform", $db);
$checkUserNameQuery = "SELECT username FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWordQuery = "SELECT password FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkPassWord = mysql_query($checkPassWordQuery);
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
$AdminChanges = "AdminChanges.php";
}
else
{
$AdminChanges = "InvalidLogin.html";
}
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<form action = <?php PrepSQL($AdminChanges); ?> method="post">
username: <input type="text" name="username" />
password: <input type="text" name="password" /> <br/>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
Two problems are joining forces to cause this error. First, your PrepSQL function does not echo the response, and neither does the code that calls it. You need to echo or print the response so that it appears in your generated HTML.
<?php echo PrepSQL($AdminChanges); ?>
Second, you need to encapsulate that value of the action attribute in double-quotes, like this:
<form action = "<?php echo PrepSQL($AdminChanges); ?>" method="post">
Also note that your code assumes that your mysql_query() statements were successful. For troubleshooting purposes, you should at least add an or die(mysql_error()) statement to the end of the mysql_query() lines. This will allow your code to provide some feedback when the query fails.
Additionally, please note that your query-handling method will never result in a valid login response.
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWord = mysql_query($checkPassWordQuery);
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
mysql_query() returns a MySQL resource, not a single field from the database. Your code attempts to compare that resource to the supplied username and password, and the comparison will always fail. For details about handling the results of mysql_query() see the documentation.
Replace:
PrepSQL($AdminChanges);
with:
print PrepSQL($AdminChanges);
Try this:
<form action = "<?php echo PrepSQL($AdminChanges); ?>" method="post">
You need to echo the value.
There are 2 errors I noticed:
Your $_POST['submit'] if statement doesn't let $AdminChanges be set for the form unless it has already been submitted.
To fix this you could change your if submit statement to just redirect to your invalid login page like so:
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
//Correct info do what you need to here
}
else
{
header("Location: InvalidLogin.html");
exit();
}
And also:
You need to change the action to go post to this page.
<form action="<? $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">