Selecting multiple data from a database through PHP - php

I have a search form that is able to retrieve the username of a user, however I can't figure out how to get it to return more than that, I want it to display the first names and last names too.
Below is the code at the minute that works, but when I try and add in more variables, for example if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?")) then it doesn't return anything at all and asks to insert a search query.
I have also tried if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE %?%")) and LIKE "%?%")), but no results.
search.php
<?php
include 'connection.php';
if(isset($_POST['searchsubmit']))
{
include 'searchform.php';
$name=$_POST['name'];
if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?"))
{
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($personresult);
$stmt->fetch();
?>
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2>
<BR>
<?php
print_r($personresult);
?>
</center>
<?php
}
else
{
echo "<p>Please enter a search query</p>";
}
}
else
{
echo "NOT SET!";
}

You are only calling Username .. You need to be calling *
SELECT * FROM users WHERE Username LIKE ?
This is my personal script I use:
<?php
$dbservername = "localhost";
$dbusername = "db_user";
$dbpassword = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!empty($_POST["username"])) {
$username = $_POST["username"];
}
if (!empty($_POST["password"])) {
$password = $_POST["password"];
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row["Username"] . " " . $row["Firstname"] . " " . $row["Lastname"] . "<br>";
if ($row["Username"] == $username && $row["Password"] == $password) {
echo "success";
// do more stuff here like set session etc
} else {
$echo "incorrect username and/or password";
}
}
}
?>

Are you initializing the statement object with mysqli_stmt_init?
See mysqli_stmt_init and mysqli-stmt.prepare

If the database server cannot successfully prepare the statement,
PDO::prepare() returns FALSE or emits PDOException (depending on error
handling)
add this line in connection.php right after creating connection object:
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
At least, you can trace possible errors

<?php
include 'connection.php';
if( isset( $_POST['searchsubmit'] ) ) {
include 'searchform.php';
$name=$_POST['name'];
if ( $stmt = $connection->prepare ("SELECT `Username`,`firstname`,`lastname` FROM `users` WHERE `Username` LIKE ?") ) {
/* not 100% sure about whether this is required here like this or not but usually a like expression uses '%' as a wildcard */
$var='%'.$name'.%';
$stmt->bind_param('s', $var );
$res=$stmt->execute();
/* 3 columns selected in query, 3 columns bound in results */
$stmt->bind_result( $personresult, $firstname, $lastname );
if( $res ){
$stmt->fetch();
echo "
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2><!-- 3 columns/variables -->
{$personresult},{$firstname},{$lastname}
<BR>
</center>";
}
} else {
echo "<p>Please enter a search query</p>";
}
} else {
echo "NOT SET!";
}
$stmt->close();
$connection->close();
?>

Related

Why isn't my code posting data from my database?

So in my login page form members, I'm trying to dynamically pull data from the SQL database depending on the user who logged in. I determine which user is logged in by using session variables. But, the following code to retrieve name from database comes out blank, could someone explain why?
<tr>
<td>Name</td>
<td>
<?php
$offset = $argv[0];
$connect = mysqli_connect("****.****", "*****", "******", "****");
$output = '';
if(isset($_SESSION["username"])){
$username = $_SESSION["username"];
}
else {
$username = $_SESSION["regusername"];
}
$query = "SELECT name FROM users WHERE username = $username $offset";
$output = mysqli_query($connect, $query);
echo $output;
?>
</td>
</tr>
Use a prepared statement first and foremost like this:
<?php
$conn = mysqli_connect("****.****", "*****", "******", "****");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_SESSION["username"])){
$username = $_SESSION["username"];
}
else {
$username = $_SESSION["regusername"];
}
$stmt = $conn->prepare("SELECT name FROM `users` WHERE username=?");
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->bind_result($output);
while($stmt->fetch()) {
echo $output;
}//end while
$stmt->close();
?>

Simple search function return always 0 results

I have this php code
if(isset($_POST['submit'])){
$likeString = '%' . $_POST['search'] . '%';
$query = $conn->prepare("SELECT * FROM images WHERE image_caption LIKE ?");
$query->bind_param('s', $likeString);
$query->execute();
var_dump($likeString);
if (!$query) {
printf("Query failed: %s\n", $mysqli->error);
exit;
}
if($res->num_rows > 0) {
while ($row = $res->fetch_assoc()) {
echo "<br>Title: " . $row['image_caption'];
}
} else {
echo " <br> 0 results";
}
}
var_dump($likeString) shows the word which I've posted via search form correctly. Also I've tried in phpmyadmin directly to run this query
SELECT *
FROM images
WHERE image_caption LIKE "%Volvo%"
And I've received 1 result which is correct. On page I see 0 results. Tried to play with fetch:
$res->fetch_assoc()
$res->fetchAll()
$res->fetch()
none of them show any result. I'm sure is something very silly and simple mistake but can't see it. Please help on this.
I don't have Call to a member function bind_param() on a non-object It was my mistake while I've made proposed changes from one of the answer. Problem still remains - 0 Results
UPDATE: Current code
$likeString = "%{$_POST['search']}%";
$query = $conn->prepare("SELECT * FROM images WHERE image_caption LIKE ? ");
$query->bind_param('s', $likeString);
$query->execute();
if($query->num_rows > 0) {
while ($row = $query->fetch()) {
echo "<br>Title: " . $row['image_caption'];
}
} else {
echo " <br> 0 results";
}
}
UPDATE 2: DB connection checked-> result is Connected successfully
$servername = "localhost";
$username = "mydbUsername"; // it's changed for the question
$password = "myPass"; // it's changed for the question
$dbname = "myDbName"; // it's changed for the question
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
You are using $res while it is not defined... You must use $query instead.
Next time turn on error reporting to see such silly bugs
try this : (update your code)
$likeString= "%{$_POST['search']}%";
$stmt = $db->prepare("SELECT * FROM images WHERE image_caption LIKE ?");
$stmt->bind_param('s', $likeString);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM))
{
foreach ($row as $r)
{
echo "<br>Title: " . $r['image_caption'];
}
print "\n";
}
OR
<?php
$conn = new mysqli("localhost","mydbUsername","myPass","myDbName");
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$query = "SELECT * FROM images WHERE image_caption LIKE %".$_POST['search']."%";
if ($result = $conn->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo "<br> Title: ". $row["image_caption"]);
}print "\n";
/* free result set */
$result->free();
}
/* close connection */
$conn->close();
?>

PHP to mySQL check if user exists

I have a script that updates/creates user from an iOS device. Now i want to have the script also check if the user already exists in the database. I am going to restrict this to username for now, so no more than ONE unique username may exist. I have an if-statement in my PHP but i cannot get it to work - help please :).
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = 'dbname';
$db_user = 'dbuser';
$db_password = 'dbpass';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
$userexists = mysql_query("SELECT * FROM users WHERE username='$username'");
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
}
if(mysql_num_rows($userexists) != 0) {
echo '{"success":0,"error_message":"Username Exist."}';
}
else {
$stmt = $mysqli->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$password = md5($password);
$stmt->bind_param('sss', $username, $password, $email);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
}
else {
echo '{"success":0,"error_message":"Username Exist."}';
}
}
}
else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Username."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
You could SELECTthe table before trying to insert username. If it already exists (= you have a result) you dont simply insert.
Better yet, use ON DUPLICATE IGNORE or something like that.

PHP Log in to show details

The website has a login system, however when a user logs into the website I simply want their details to appear on the next page. This is my code I so far. Problem is, I only want to display the logged in users details, not all the databases details.
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "loginsystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM members";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["firstname"]. " " . $row["lastname"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
LOG IN SYSTEM
<?php
session_start();
if (isset($_POST['username'])) {
include_once("dbConnect.php");
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
$usname = mysqli_real_escape_string($dbCon, $usname);
$paswd = mysqli_real_escape_string($dbCon, $paswd);
$sql = "SELECT id, username, password FROM members WHERE username = '$usname' AND activated = '1' LIMIT 1";
$query = mysqli_query($dbCon, $sql);
$row = mysqli_fetch_row($query);
$uid = $row[0];
$dbUsname = $row[1];
$dbPassword = $row[2];
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && password_verify($paswd,$dbPassword)) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: MemberDetails.php");
} else {
echo "Oops that username or password combination was incorrect.
<br /> Please try again.";
}
}
?>
Add
session_start();
to the top of the page and then on the next page as well and then you will be able to carry over those variables once they are set.
For example:
$_SESSION['user'] = $_POST['user'];
Then on the next page call:
echo $_SESSION['user'];
You first have to implement the user login part. and after that, get the specified user id or login credentials and use that in your query.
In your LOG IN SYSTEM file, put session_start(); before including the db connection.
Then in the member details page do this:
session_start(); //put this on the first line.
Then your query will now look like below:
<?php
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "loginsystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user_id = $_SESSION['id'];
$sql = "SELECT user_id, firstname, lastname FROM members WHERE user_id = ".$user_id;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["firstname"]. " " . $row["lastname"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Database structure

php login form not working correctly

I'm trying to create a simple login functionality but it's not working, and I'm relatively new to mysqli so please bear with me. I just want to check if the email address and password are correct and if they are then log the user in. Thanks in advance.
Here is my login code that checks the credentials:
UPDATED CODE - I added the report all and I'm now getting internal server error
<?php
require_once 'connect.php';
mysqli_report(MYSQLI_REPORT_ALL);
session_start();
if (!isset($_SESSION['email'])) {
$e = trim($_REQUEST['email']);
$email = $mysqli->real_escape_string($e);
$p = trim($_REQUEST['password']);
$password = $mysqli->real_escape_string($p);
/*
if ($result = $mysqli->query("SELECT email, password, user_id" .
" FROM users" .
" WHERE email = '$email' AND password = '$password'")) {
printf("Select returned %d rows.\n", $result->num_rows);
echo 'Total results: ' . $result->num_rows;
}
*/
if ($stmt = $mysqli->prepare("SELECT email, password, user_id FROM users WHERE email=? AND password=?")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $email, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($email, $password);
/* fetch value */
$stmt->fetch();
if ($stmt->num_rows==1) {
$row = $stmt->fetch_assoc(MYSQLI_NUM);
$user_id = $row['user_id'];
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
header("Location: home.php");
/* close statement */
$stmt->close();
} else {
printf("Error message: %s\n", $mysqli->error);
}
/*
if ($result->num_rows==1) {
$row = $result->fetch_assoc(MYSQLI_NUM);
$user_id = $row['user_id'];
if ($query_group = $mysqli->query("SELECT *" .
" FROM user_groups" .
" WHERE user_id = '".$user_id."'")) {
//No more setcookie
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
} else {
echo 'Did not work';
}
}
*/
/* free result set */
// $result->close();
}
}
?>
And here is connect.php to connect to the database:
<?php
$mysqli = new mysqli("data", "username", "password", "db");
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
?>
did you try to remove one of the brackets in the end of ypur code. I guess you have to remove one of them.

Categories