New $_SESSION variable not created after query? - php

I'm trying to build a login process where, by using $_SESSION variables, the login credentials of the user are stored and used to show their relevant data from the database on screen (i.e. they will only see the school data that they work for).
<?php
session_start();
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
{
$host = "xxx";
$username = "xxx";
$password = "xxx";
$database_name = "xxx";
$table_name = "xxx";
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
$query = "SELECT Class FROM $table_name WHERE Initials = '".
$_SESSION['Initials']."' AND staff LIKE '%".$_SESSION['Surname']."'";
$result = mysql_query($query);
$class = mysql_fetch_array($result);
$count = mysql_num_rows($result);
if($count === NULL)
{
echo "ERROR";
}
else
{
$_SESSION['Class'] = $result;
echo "Class added to sessions";
}
}
?>
My initial problem where the query couldn't recognize the session variables was easily solved by adding the correct brackets for the if-statement. My next problem that has arisen here is that even though the query should be successfull (I don't receive an error message saying 'ERROR' when the $count is either FALSE or NULL) it's not creating the result array into a new session, because when I print the session array on a new page it's still only carrying over the 'Initials' and 'Surname' sessions.
What do I need to change to my query, or post-query process in order for that array (because it's bound to throw up multiple results) to be made into a new session?
Many thanks for the answers to my initial problem!

if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
// code
}
u need { } brackets
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
$host = "xxxxx"; $username = "xxxxx"; $password = "xxxxx";
is
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
$host = "xxxxx";
}
$username = "xxxxx";
$password = "xxxxx";

I've found the answer - it turned out that I wasn't treating one of the session variables as a proper array and thus wouldn't load properly. I've added my script below so that people with similar problems in the future can use it as a reference point:
<?php
session_start();
// Server Details //
$host = "---";
$username = "---";
$password = "---";
$database_name = "---";
$table_name = "---";
// Connect Command //
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
// Query to call up the unique school name //
$query_school = mysql_query("SELECT DISTINCT School FROM $table_name
WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_school = mysql_result($query_school, 0);
// Query to call up the unique centre no //
$query_centreno = mysql_query("SELECT DISTINCT CentreNo FROM
$table_name WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_centreno = mysql_result($query_centreno, 0);
// The newly created sessions for school info //
$_SESSION['---'] = $result_school;
$_SESSION['---'] = $result_centreno;
// Query to call up the array of classes //
$query_class = mysql_query("SELECT Class FROM $table_name WHERE
Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$query_class__array = array();
while($row = mysql_fetch_assoc($query_class))
$query_class_array[] = $row;
$_SESSION['---'] = $query_class_array;
?>

Related

Seems like SQL's WHERE clause and JOIN do not work together

I am trying to make a basic forum, and I am having trouble printing just one row in SQL. Here is my PHP:
<?php
ob_start();
$host = "localhost";
$user = "root";
$pass = "MYPASSWORD";
$db = "MYDB";
$conn = mysqli_connect($host, $user, $pass, $db) or die("cannot connect to database.");
$sql = "SELECT * FROM forum WHERE fid = '{$fid}' JOIN user ON forum.creator=user.id;";
$result = mysqli_query($conn, $sql);
if ($result == true) {
while ($row = mysqli_fetch_assoc($result)) {
print "<h1>{$title}</h1>";
}
}
else {
print "failed to reach post.";
}
ob_flush();
?>
To help out, I believe everything works except for $sql. I have enabled ini_set('display_errors',1); but I am getting no error messages (excpet for my own that I made for the else statement).
Try this query
SELECT * FROM forum JOIN user ON forum.creator=user.id WHERE fid = '{$fid}' ;

The same script in PHP in localhost doesn't working online

I upload my script in my server and I made a new database in the same server.
the connection with database is working, but when the two script check or insert new value on the database doesn't working, but in localhost yes!!
<?php
require 'client/facebook.php';
$app_id = "***";
$secret = "***";
$app_url = "***";
// Create our Application instance
///jump the code
////////////////////////////////
$sdb = "***";
$db = "***";
$userdb = "***";
$passdb = "***";
$dblink = mysql_connect($sdb,$userdb,$passdb);
$seldb = mysql_select_db($db);
$username = $username; //user data
$UIDfaceboook =$id; //UID USER FACEBOOK FROM API
$user_type ="aa"; //USER DATA
$connection =""; //variable for start function check UID
$checkUIDdb ="INATTESA"; //check if exist the UID facebook
$insertnewuser ="";
$loadspecific ="inattesa";
///
///CHECK CONNECTION WITH DATABASE
///
$mysqlConnection = mysql_connect($sdb, $userdb, $passdb);
if (!$mysqlConnection)
{
echo "NO DATABASE FOUND, CHECK USER, PASS, DB";
}
else
{
echo "connection with database is ";
echo $connection = "ok";
mysql_select_db($db, $mysqlConnection);
}
//////////////////////////THIS FUNCTION DOESN'T WORK ONLINE
if ($connection = "ok"){
$con=mysqli_connect($sdb,$userdb,$passdb,$db);
$check="SELECT * FROM tabletest WHERE UIDfacebook = '$UIDfaceboook'";
$rs = mysqli_query($con,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
echo "UID IN THE DATABASE ";
echo $checkUIDdb = "found";
}
else
{
echo "UID IN THE DATABASE ";
echo $checkUIDdb = "nofound";
}
}
///////////////THIS FUNCTION DOESN'T WORK ONLINE, and doesn't insert values
if($connection == "ok" && $checkUIDdb == "nofound"){
$username = strip_tags(mysql_real_escape_string($username));
$UIDfacebook = strip_tags(mysql_real_escape_string($UIDfaceboook));
$user_type = strip_tags(mysql_real_escape_string($user_type));
$sql = mysql_query("INSERT INTO `$db`.`tabletest` (`id`,`username`,`UIDfacebook`,`user_type`) VALUES ('','$username','$UIDfaceboook','$user_type');");
if($sql){
//The query returned true - now do whatever you like here.
echo $connection = "SAVE USERNAME, UID FACEBOOK AND USER TYPE ON DATABASE";
echo $loadspecific ="caricadati";
echo $insertnewuser = "yes";
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
}
}else{
echo $connection = " CORRECT LOGIN WITH FACEBOOK";
}
mysql_close($dblink);
//Close off the MySQL connection to save resources.
?>
the echo php on my server said " connection with database is okUID IN THE DATABASE nofound" so, I don't understand when the variable $connect, $checkUIDdb is working don't load the script for insert a new user... I try to add my UID facebook in my database to check if the script jump this step, but the script ignore the database... just said that...
maybe the first problem is on $check="SELECT * FROM tabletest WHERE UIDfacebook = '$UIDfaceboook'";
but in localhost works..
thank you very much, i don't know what I can do...
first error i saw was this one:
//////////////////////////THIS FUNCTION DOESN'T WORK ONLINE
if ($connection = "ok"){
i guess you should edit this to
if ($connection == "ok"){
so you ask if $connection has the value "ok" and not if the allocation of "ok" to $connection has been done successfully.
Second error could be a mixture of "mysql" and "mysqli"...
hth

Returning Query Result

So, I'm writing this application in PHP where the user has a "Student's Name" and each user has a unique student name. So, before I go any further with my problem, here is the code
*Note I've already prevented the SQL injections
function hello($username123) {
// Connect to Database //
$host3 = "db";
$username3 = "db";
$password3 = "db";
$db3 = "db";
$con3 = mysqli_connect($host3,$username3,$password3,$db3) or die("Can not connect to Server.");
$query3 = mysqli_query($con3,"SELECT student1 FROM users WHERE username = '$username123'");
$student1name = "$query3";
return $student1name;
So, the person enters the username which the registered before hand and each user has a student name.I start a query which selects student1 and student1 is equal to student1name. Student 1 name is then defnied as query3. When I test it all out, all I get is (null).. Does anyone know the problem? Thank you!
I suspect what you want is something like this:
function hello($username123) {
// Connect to Database //
$host3 = "db";
$username3 = "db";
$password3 = "db";
$db3 = "db";
$con3 = mysqli_connect($host3,$username3,$password3,$db3) or die("Can not connect to Server.");
$query3 = mysqli_query($con3,"SELECT student1 FROM users WHERE username = '$username123'");
while ($row = mysqli_fetch_array($query3))
{
$student1name = $row['student1'];
}
return $student1name;
This will put the contents of the last returned row of your query, column "student1", into the variable $student1name, and return it.
You are not fetching data from result. Try this:
function hello($username123) {
// Connect to Database //
$host3 = "db";
$username3 = "db";
$password3 = "db";
$db3 = "db";
$con3 = mysqli_connect($host3,$username3,$password3,$db3)
if (!$con3)
throw new Exception("Connection error");
$result = mysqli_query($con3,"SELECT student1 FROM users WHERE username = '$username123'");
if ($result)
return $result->fetch_object();
else
throw new Exception("Query error: " . mysqli_error($con3));
}

Basic PHP-script doesn't work

I'm new to PHP and SQL but I'm trying to create a simple PHP-script that allows a user to login to a website. It doesn't work for some reason and I can't see why. Every time I try to login with the correct username & password, I get the error "Wrong Username or Password". The database-name and table-name are correct.
connect.php:
<?php
$db_host = 'localhost';
$db_name = 'app';
$db_user = 'root';
$db_pass = '';
$tbl_name = 'users';
// Connect to server and database
mysql_connect("$db_host", "$db_user", "$db_pass") or die("Unable to connect to MySQL.");
mysql_select_db($db_name)or die("Cannot select database.");
// Info sent from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql = ("SELECT * FROM $tbl_name WHERE username='$user' and password='$pass'");
$result= mysql_query($sql);
$count 0= mysql_num_rows($result);
if($count==1){
// Register $user, $pass send the user to "score.php"
session_register("user");
session_register("pass");
header("location:score.php");
}
else
{
echo "Wrong Username or Password";
}
?>
score.php:
<?php
session_start();
if(!session_is_registered(user)){
header("location:login.html");
}
?>
<html>
<body>
<h1>Login Successful</h1>
</body>
</html>
I hope someone can find my mistake, thanks!
FYI session_register and session_is_registered are deprecated and will be removed from PHP. Also try to change your code to use mysqli or PDO. Plenty of articles explain how to do it. Finally, make sure you escape input from the user ($_POST array) because you never know what the user will send and you don't want to be prone to SQL injections. You really do not want to store passwords in clear text, so using SHA1 or MD5 is best.
Having written the above, your code becomes (you can use the $_SESSION global array directly):
connect.php:
<?php
$db_host = 'localhost';
$db_name = 'app';
$db_user = 'root';
$db_pass = '';
$tbl_name = 'users';
// Connect to server and database
mysql_connect($db_host, $db_user, $db_pass) or die("Unable to connect to MySQL.");
mysql_select_db($db_name) or die("Cannot select database.");
// Info sent from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql = "SELECT * FROM $tbl_name "
. "WHERE username = '$user' "
. "AND password = sha1('$pass')";
$result = mysql_query($sql);
// There was an extra 0 here before the equals
$count = mysql_num_rows($result);
if ($count==1)
{
// Register $user, $pass send the user to "score.php"
$_SESSION['user'] = $user;
// You really don't need to store the password unless you use
// it somewhere else
$_SESSION['pass'] = $pass;
header("location: ./score.php");
}
else
{
echo "Wrong Username or Password";
}
?>
score.php:
<?php
session_start();
if (!isset($_SESSION['user']))
{
header("location:login.html");
}
?>
<html>
<body>
<h1>Login Successful</h1>
</body>
</html>
A couple of things
Change this line to the one with error checking i have put below it
$result= mysql_query($sql);
$result= mysql_query($sql) or die(mysql_error());
chances are there is an sql error and you are not picking it up, so the result will always have 0 rows
Also not sure if this line is a typo or not, there shouldn't be a 0 in there
$count 0= mysql_num_rows($result);

Comparing database stringvalue with new stringvalue

Here is what I'm trying to do: When user adds a contact to his list, the number of this contact gets run by with the numbers in the database and it gives feedback if the user is already in the database or not. Right now I always get back "User is in database" even though he isn't. Then again I'm not that well acquainted with php. I changed the code a bit again, now it doesn't work at all, because it doesn't like the part
$number = ($_GET["number"] from $DB_Table);
Full code
<?php
$DB_HostName = "localhost";
$DB_Name = "db";
$DB_User = "user";
$DB_Pass = "pw";
$DB_Table = "contacts";
$number = ($_GET["number"] from $DB_Table);
$fnumber = ($_GET["fnumber"]);
if ($number == $fnumber) {
echo "This user is already in database";
} else {
echo "This user isn't in the database";
}
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
mysql_close($con);
?>
I don't actually see you executing the database query. You could do something like this:
<?php
$DB_HostName = "localhost";
$DB_Name = "db";
$DB_User = "user";
$DB_Pass = "pw";
$DB_Table = "contacts";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$fnumber = mysql_real_escape_string($_GET["fnumber"]);
$result = mysql_query("SELECT * FROM $DB_Table WHERE Something = '$fnumber'", $con);
if ($result) {
// Check the number of rows in the result set
if (mysql_num_rows($result) > 0) {
echo "This user is already in database";
}
else echo "This user isn't in the database";
}
mysql_close($con);
?>
This is not valid PHP code: $number = ($_GET["number"] from $DB_Table);
$_GET["number"] represents the value of the "number" parameter that you find in the url of your page.
Example: http://example.com/index.php?number=7 so $_GET["number"] is 7.
In your code, $DB_Table is a just a string ("contact") and "from" does not fit there using php syntax.
mysql_select_db($DB_Name,$con) or die(mysql_error());
is valid PHP but you are not doing anything with what you get from the database. I suggest you at least take a look at this tutorial php mysql select

Categories