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

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();
?>

Related

How can I connect one row to tables in database?

I'm currently working on a system for our school, and I'm having a signup/login/attendance system.
The problem is that I want to make a user which is in a row of my table to connect to another table. It is for him only the one who can access that table because it seems that whenever we login another user it redirects on the same webpage.
Is there a way I can fix that?
<?php
$mymail = $_POST["mymail"];
$mypass = $_POST["mypass"];
echo "$mymail";
//database connection to check inside table and query email and password
$servername = "localhost";
$username = "root";
$password = "admin";
$dbname = "sistema";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM userlogin where mymail ='" . $mymail . "' and mypass = '" . $mypass . "'";
$result = $conn->query($sql);
// echo $sql;
if ($result->num_rows > 0) {
// output data of each row
// while($row = $result->fetch_assoc()) {
// echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["idnumber"]. "<br>";
// }
header("Location: http://localhost/sistema/attendance/index.php"); /* Redirect browser */
} else {
header("Location: http://localhost/sistema/signup/index2.html"); /* Redirect browser */
// echo "0 results";
}
$conn->close();
?>
//THIS IS JUST THE CONNECTION TO THE DATABASE AS WELL AS THE QUERY, I separated the HTML form
you can store him user id in a session
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
//after login that user
$_SESSION["id"] = $_Post['id'];
$_SESSION["id"] = $_Post['username'];
?>
you have to start session every page and you can use that user id anyway on your website
to call $_SESSION["id"]
if he click logout
unset($_SESSION["id"]); & unset($_SESSION["id"]);
<?php
//Start session
session_start();
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn){
die('not conected :'.mysqli_error());
}
#$conn =new mysqli("localhost","root","","mystudy");
$email = $_POST['email'];
$password = $_POST['psw'];
$qry="SELECT * FROM users_table WHERE user_email='$email' AND user_password='$password'";
$result=mysqli_query($conn,$qry);
if($result) {
if(mysqli_num_rows($result) > 0) {
//Login Successful
$users = mysqli_fetch_assoc($result);
session_regenerate_id();
$_SESSION['SESS_user_ID'] = $users['id'];
$_SESSION['SESS_user'] = $users['user_name'];
$_SESSION['SESS_user_EMAIL'] = $users['user_email'];
session_write_close();
header("Location: /any your path url/page.php");
}else{
header("Location: /any your path url/error_page.php");
}
?>
index.php
<?php
//Start session
session_start();
$userid=$_SESSION['SESS_user_ID'];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM users_table WHERE id='$userid'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
?>
<table>
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
</tr>
<tr>
<?php
while($row = mysqli_fetch_assoc($result)) {
<td><?php echo $row["id"];?></td>
<td><?php echo $row["username"];?></td>
<td><?php echo $row["email"];?></td>
<?php } }?>
</tr>
</table>

Php getting id of current user not working

I was trying to make a page where you can log in and then change your nickname or/and password. Everything in mySQL database, but when I try to save the id to session variable, it doesn't work. Any suggestions?
I am using XAMPP, users is my table in database users, I'm not posting login form code, because it's very simple.
Everything is connected, code doesn't give any warnings or errors.
login.php (fragment):
$sql = "SELECT * FROM users WHERE nickname = '$myusername' and pass = '$mypassword' and confirmed = 1";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
$logged = true;
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"];
$_SESSION['currentId'] = $row["id"];
echo 'Id: ' . $_SESSION['currentId'];
}
}else {
$error = "Your Login Name or Password is invalid";
}
}
change.php (whole):
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Users";
$currentId = $_SESSION['currentId'];
if($currentId<1){echo 'No Id.';}
else {echo 'CurrentId: ';
echo $currentId;}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully <br>";
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$aCUname = mysqli_real_escape_string($conn,$_POST['CUname']);
$aCUpass = mysqli_real_escape_string($conn,$_POST['CUpass']);
$sql = "UPDATE users SET nickname = '$aCUname', pass = '$aCUpass' WHERE id = '$currentId';";
$result = mysqli_query($conn,$sql);
echo 'Updated successfully.';
}
?>
Thanks for help.
I got a solution. I just had to delete
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
from login.php. Thanks to #Shashikumar Misal !

show results with same username php

I have a database which stores data. How can I view data in my database with the same username as my session? What I have tried is below. There is a session and the username is uploading in each row in the database.
This is what I'm trying to do: say I logged in as jack I typed data in and sent it to the database. It saves the name as jack and then only views the results with jack. But it is saying 0 results. Why?
<?php
session_start();
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
echo "$username";
}
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "score";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM all_scores WHERE username = '".$username."' ORDER BY id DESC LIMIT 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p></p>";
echo "". $row["name"]. "";
echo "<p>". $row["description"]. "</p>";
}
} else {
echo "0 results";
}
$conn->close();
?>
you have two mistakes
1- SQL syntax error, correct syntax is
$sql = "SELECT id, name, description FROM all_scores WHERE username = '".$username."'";
2- the variable $username is overwritten by the username of the database
try this:
$sql = "SELECT id, name, description FROM all_scores WHERE username = '".$_SESSION['username']."'";

Selecting multiple data from a database through 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();
?>

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

Categories