Can't fetch rows from MySQL database - php

I'm a bit rusty on mysql, especially now that it's mysqli... Nothing happens in the script below, the variables $row[username] etc are empty. What am I doing wrong?
<?php
session_start();
include_once('./db_config.php');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = md5(mysqli_real_escape_string($conn, $_POST['password']));
$query = "SELECT * FROM players WHERE username = '".$username."' AND password = '".$password."'";
if($res = mysqli_query($conn, $query))
{
$row = mysqli_num_rows($res);
$_SESSION['Username'] = $row['username'];
$_SESSION['uID'] = $row['id'];
$_SESSION['Join_Date'] = $row['join_date'];
mysqli_free_result($res);
header('Location: ../index.php');
} else
{
echo mysqli_error($conn);
}
?>

You are not fetching the records instead you are doing myql_num_rows(this will give only no of record)
use this to fetch records
$row = mysqli_fetch_array($res,MYSQLI_ASSOC);
<?php
session_start();
include_once('./db_config.php');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = md5(mysqli_real_escape_string($conn, $_POST['password']));
$query = "SELECT * FROM players WHERE username = '".$username."' AND password = '".$password."'";
if($res = mysqli_query($conn, $query))
{
$row = mysqli_fetch_array($res,MYSQLI_NUM);
$_SESSION['Username'] = $row['username'];
$_SESSION['uID'] = $row['id'];
$_SESSION['Join_Date'] = $row['join_date'];
mysqli_free_result($res);
header('Location: ../index.php');
} else
{
echo mysqli_error($conn);
}
?>

Related

Cannot redirect to user_panel page after login ... header() not working

<?php
if(isset($_POST['submit'])){
$con=mysqli_connect("localhost","root","") or die("Failed to connect to MySQL: " .mysqli_connect_error());
$db=mysqli_select_db($con,"users") or die("Failed to connect to MySQL: " .mysqli_connect_error());
$count=0;
$username = $_POST['username'];
$password = $_POST['password'];
$query1 = "SELECT * FROM user_info WHERE Username= '$_POST[username]' && Password= '$_POST[password]'";
$res = mysqli_query($con, $query1) or die(mysqli_connect_error());
$count = mysqli_num_rows($res);
if($count>0){
session_start();
$_SESSION['username'] = $username;
header ("Location: user_panel.php");
}
else{
echo "Incorret username or password ...";
}
}
?>
use fullpath in header location like this
<?php
$baseurl = "http://examplesite.com/";
header("location: ".$baseurl."user_panel.php");
?>
You can achieve by javascript also.
window.location.href='user_panel.php';

mysqli conversion fetch query

How can i convert this statement into mysqli. i tried converting it but is not working. what am i missing. I want to connect to a login form.
This is the code i converted.
<?php
include('admin/dbcon.php');
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
/* teacher */
$query_teacher = mysql_query("SELECT * FROM teacher WHERE username='$username' AND password='$password'")or die(mysql_error());
$num_row_teacher = mysql_num_rows($query_teacher);
$row_teahcer = mysql_fetch_array($query_teacher);
/* admin */
$query_admin = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'")or die(mysql_error());
$num_row_admin = mysql_num_rows($query_admin);
$row_admin = mysql_fetch_array($query_admin);
if ($num_row_teacher > 0){
$_SESSION['id']=$row_teahcer['teacher_id'];
echo 'true';
}else if ($num_row_admin > 0){
$_SESSION['id']=$row_admin['user_id'];
echo 'true_admin';
}else{
echo 'false';
}
?>
This is the converted mysqli but i cannot still log on am i missing something. I will be very grateful if you can help me solve this.
<?php
// establishing the MySQLi connection
$con = mysqli_connect("localhost","root","","retreat");
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established: " . mysqli_connect_error();
}
// checking the user
session_start();
$username = mysqli_real_escape_string($con,$_POST['username'];
$password = mysqli_real_escape_string($con,$_POST['password'];
/* teacher */
$query_teacher = "SELECT * FROM teacher WHERE username='$username' AND password='$password'";
$num_row_teacher = mysqli_query($con,$query_teacher);
$row_teahcer = mysqli_num_rows($num_row_teacher);
/* admin */
$query_admin = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$num_row_admin = mysqli_query($con,$query_admin);
$row_admin = mysqli_num_rows($num_row_admin);
if ($row_teahcer > 0){
//$_SESSION['user_email']=$email;
$_SESSION['']=$row_teacher['teacher_id'];
echo 'true';
}else if ($num_row_admin > 0){
$_SESSION['id']=$row_admin['user_id'];
echo 'true_admin';
}else{
echo 'false';
}
?>
<?php
//db details
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'retreat';
//Connect and select the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
/* teacher */
$query = $db->query("SELECT * FROM teacher WHERE username='$username' AND password='$password'")or die(mysqli_error());
$num_row_teacher = mysqli_num_rows($query);
$row_teahcer = mysqli_fetch_array($query);
/* admin */
$query_admin = $db->query("SELECT * FROM users WHERE username='$username' AND password='$password'")or die(mysqli_error());
$num_row_admin = mysqli_num_rows($query_admin);
$row_admin = mysqli_fetch_array($query_admin);
if ($num_row_teacher > 0){
$_SESSION['id']=$row_teahcer['teacher_id'];
echo 'true';
}else if ($num_row_admin > 0){
$_SESSION['id']=$row_admin['user_id'];
echo 'true_admin';
}else{
echo 'false';
}
enter code here
?>
Your are missing
$row_teahcer=mysqli_fetch_array($num_row_teacher);
$row_admin=mysqli_fetch_array( $num_row_admin);

Ajax post json response issue

I have an issue with ajax response. I am using custom query for fetch result from database. Json response always shows null value while query is running successfully. Here is my code:
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
while($fetch = mysql_fetch_array($query))
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
#Amandhiman i did not get what is the use of if statement with in the while
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
the mention code definitely works for you
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
Try with the below code, (mysql is deprected), working for me with my test database table (Debug it, var_dump $result, $result->fetch_assoc(), $result->num_rows)
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
try this
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
echo json_encode($arr);
}
First of all start session before playing with it on the top of page
session_start();
check your database connectivity.
Use print_r($arr) for testing your array();
first off all you are using session variable . to use session variable you need to initialize it by session_start()
you are using key in the array in this way it will return the last inserted record in the array . try this code
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
// if wants to use session then start session
session_start(); // else it will return null
$_SESSION['ID']= $fetch['id']; // i don't know why this ??
// $arr['id'] = $_SESSION['ID']; comment this
$arr[] = array('msg'=>'succsee','ID'=>$fetch['id']);
}
else
{
$arr[]= array('msg'=>'fail','ID'=>null);
}
}
echo json_encode($arr);
}

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

Undefined index: userID error

Upon Logging in, I have the userID stored in the SESSION. However when I call updateMarkerlocations.php it says userID is undefined. Not sure what I'm missing.
login.php
session_start();
if (!isset($_POST['submit'])){
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from userinfo WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
$row = $result->fetch_assoc();
setcookie("username", time() +60*60*24*30*365);
$_SESSION['userID'] = $row['userID'];
echo "<p>Logged in successfully!, Please close the window</p>";
}
}
?>
updateMarkerLocations.php
<?php
include 'db_const.php';
function insertMarkerLocations()
{
$markerCount = 0;
if (isset($_POST['markerCount']))
$markerCount = $_POST['markerCount'];
if(isset($_SESSION["userID"]))
{
$userID = $_SESSION["userID"];
}
$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
$userID = $_POST['userID'];
for($i=0 ; $i < $markerCount; $i++){
$index = $i;
++$index;
$curMarkerID = $_POST["markerID$index"];
$curLang = $_POST["lang$index"];
$curLat = $_POST["lat$index"];
// Now write the current marker details in to the db.
$query = "INSERT INTO userinfo (userID, markerID, lang, lat ) VALUES ('$userID', '$curMarkerID', '$curLang', '$curLat')";
mysql_query($query)
or die(mysql_error());
}
$msg = "SUCCESS";
return $msg;
}
$msg = insertMarkerLocations();
echo json_encode($msg);
?>
Add this at the top of each file:
if(!isset($_SESSION)) session_start();
Also, when you do:
$userID = $_POST['userID'];
you should ensure that $_POST['userID'] exists:
if(isset($_POST['userID'])) $userID = $_POST['userID'];

Categories