I've been been on this for hours trying to find the small mistake I've done and I just can't find it... All I'm doing is calling a variable as global in a function and it's just not working even though it worked fine with the function above it...
I get an error saying mysqli is null...
include 'data/mysqli_connect.php';
function process_login(){
global $mysqli;
$username = $_SESSION['username'];
$sql = "SELECT * FROM auth WHERE user='".mysqli_real_escape_string($mysqli,$username)."'";
$query = mysqli_query($mysqli,$sql);
if(mysqli_num_rows($query)>0){
$sql = "DELETE FROM auth WHERE user='".mysqli_real_escape_string($mysqli,$username)."'";
$query = mysqli_query($mysqli,$sql);
if(!$query){
die(mysqli_error());
}
}
$sql = "INSERT INTO auth (user, session) VALUES ('".mysqli_real_escape_string($mysqli,$username)."', '".$_SESSION['id']."')";
$query = mysqli_query($mysqli,$sql);
if(!$query){
echo "Can not insert info into database!<br />". mysqli_error();
}else{
header("Location:chat.php");
}
}
function logout(){
global $mysqli;
$sql = "DELETE FROM auth WHERE session='".mysqli_real_escape_string($mysqli,$_SESSION['id']). "'";
$query = mysqli_query($mysqli,$sql);
if(!$query){
echo "Can not delete info from database!";
}else{
session_destroy();
header("Location: chat.php");
}
}
function get_username(){
global $mysqli;
$sql = "SELECT * FROM auth WHERE session='".mysqli_real_escape_string($mysqli,$_SESSION['id']). "'";
$query = mysqli_query($mysqli,$sql);
$row = mysqli_fetch_array($query);
if(mysqli_num_rows($query) == "0"){
$username = "Guest";
}else{
$username = $row['user'];
}
return $username;
}
function post_message(){
global $mysqli;
$text = addslashes(htmlentities(htmlspecialchars($_REQUEST['text'])));
$sql = "INSERT INTO chat (time, user, text) VALUES ('".date("H:i")."', '".get_username()."', '".$text."')";
$query = mysqli_query($mysqli,$sql);
if(!$query){
die(mysqli_error());
}
}
mysqli_connect.php
$mysqli = mysqli_connect(localhost, "info", "info", "info");
Like I said it worked on the function above this one but not this one, it doesn't make sens... I'm guessing I have a stupid mistake in there somewhere just don't know where.
By the way,the functions that I tested and work are process_login() and logout() and get_username()
get_username() runs first then process_login(). post_message() runs from a jquery code that calls it when i press on enter that probably works fine since i can see the error code when i press enter.
Oh and sorry about the bad code formatting,not sure how to fix it on here.
Thank you for any help or advice you may find.
How/When is post_message() called? From what you edited in, I can't find anything specifically in that that would clear the $mysqli variable - but to debug it, we would need more of the program flow.
Or you could create a 'hack' in the code and within post_message() after you declare global $mysqli;, do include 'data/mysqli_connect.php'; again since the $mysqli reference to your DB connection has been lost by then. But, ideally, you need to follow the flow of your code to figure out where to fix it correctly - and your flow seems not to be able to be posted fully, or is too great to post fully here.
(Too long for a comment, so this response comes in answer form, my apologies.)
Instead of making $mysqli a global variable, try passing it as an additional parameter to your functions. I was having the same problem and that's how i solved it. ie...
function post_message($mysqli){
$text = addslashes(htmlentities(htmlspecialchars($_REQUEST['text'])));
$sql = "INSERT INTO chat (time, user, text) VALUES ('".date("H:i")."',
'".get_username()."', '".$text."')";
$query = mysqli_query($mysqli,$sql);
if(!$query){
die(mysqli_error());
}
Hope this works for you.
Related
Ok so I am trying to select values from a table in mysql using a $_post. Below I have included a basic php file without post that seems to be working fine and returns json as expected with the value of username just manually set.
echo "connection";
$connection = mysqli_connect("localhost","root","","simplifiedcoding") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
echo "statement";
$sql = "select * from volley where username = 'cmac '";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
But then when I try to set the value of username with $_Post in another tester file it doesnt work. The value is not being set as seen below. The code is meant to check if the username has been set, then execute the function using the set data.I really dont know where this is going on and I appreciate that this is a common subject matter but I have no idea what is causing this to not be set.
require_once 'connection.php';
class Get_game
{
private $db;
private $connection;
function __construct()
{
$this->db = new DB_Connection();
$this->connection = $this->db->get_connection();
echo "connected";
}
public function get_game_id($username)
{
echo "query";
//$query = "select * from volley";
$query = "select game_id from volley WHERE username = '".$username."'";
echo "result";
$result = mysqli_query($this->connection, $query) or die ("Error in Selecting " . mysqli_error($this->connection));
//create an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
return json_encode($emparray);
//close the db connection
mysqli_close($this->connection);
}
}
echo "class";
$game = new Get_game();
if (isset($_POST['username'])) {
$username = $_POST['username'];
echo "set";
if (!empty($username)) {
$game->get_game_id($username);
} else {
echo("error");
}
}
I have looked on previous answers on here but nothing seems to work. It is also quite annoying that I have other files with the same syntax but different variables to $_post that are working fine. I included a couple of echos to see where the code was failing as no errors are showing. The code creates the class fine but wont set the values. I will include a file that works fine with the same syntax below. I just can't figure out why one piece of code works fine in one instance and seems to not work at all in another with barely anything being changed.The first snippet of code works fine but I want to be able to execute the querying with a $_post value. I have tried different ways of doing this and none of them seem to work. The code is meant to return json and display it. The first snippet of code does this perfectly. I know that there is something wrong withh the $_post and issett() but i cannot figure it out
I'm trying to do a function that updates the field 'status' in the database from unpaid to paid on the click of a hyperlink/button. Here is what I'm doing but it is not working. Please help me debug my code.
function pay($idno, $secid) {
$query = "UPDATE payments SET status='paid' WHERE idNumber = '$idno' AND sec_id = '$secid'";
$result = mysqli_query($mysqli,$query); }
$sec_id = '2';
$idno= '3';
echo "<td><a href='' onclick='pay($idno, $secid);' >PAY NOW</a></td>";
}
This is what I attempted but nothing is happening. My SQL connection is correct I've checked already.
Without more information on the error it appears that your MySQL connection is undefined. You need to pass it as a parameter or reference it as a global:
function pay($idno, $secid) {
global $mysqli;
$query = "UPDATE payments SET status='paid' WHERE idNumber = '$idno' AND sec_id = '$secid'";
$result = mysqli_query($mysqli,$query); }
$sec_id = '2';
In addition, you can't call a PHP function from HTML as you are attempting to do. You must do an Ajax call to PHP from Javascript.
I have this function
function getNick($uid)
{
$sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
mysqli_real_escape_string($con,$sqli);
$resulti = mysqli_query($con,$sqli);
$rowi = mysqli_fetch_assoc($resulti);
if($resulti->num_rows > 0) return $rowi["nick"];
else return "(none)";
}
Basically it should return me nick based on user's id. Problem is that I only keep getting '(none)'. What is interesting I printed actual $sqli and copied it into phpMyAdmin and it worked as expected. I even tried to just print nick without IFs but I ended up with empty string. What might be the issue? Am I overlooking something? Thanks
<?php
$con = mysqli_connect("localhost","root","","test");
function getNick($uid,$con)
{
$sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
mysqli_real_escape_string($con,$sqli);
$resulti = mysqli_query($con,$sqli);
$rowi = mysqli_fetch_assoc($resulti);
if($resulti->num_rows > 0) return $rowi["nick"];
else return "(none)";
}
echo getNick(1,$con);
?>
it works
variable scope problem
use above method to pass connection in method or
use $GLOBALS['con'] to access connection in method getNick
I am trying to acces my connection variable while I run a while loop, yet when I try to call a function, it bogus out on me and PHP gives me the so called boolean error when I try to prepare my statement within the function.
I debugged it to the point that I know my variable $CategorieId is being pushed on and I do get a array return of $con when I do a print_r in the function itself. However when I try to acces it when I prepare my statement, it just returns me a boolean, thus creating the error in the dropdown, not being able to fill it up.
The setup is as followed.
dbControl.php
$con = mysqli_connect('localhost','root','','jellysite') or die("Error " . mysqli_error($con));
function OpenConnection(){
global $con;
if (!$con){
die('Er kan geen verbinding met de server of met de database worden gemaakt!');
}
}
functionControl.php
function dropdownBlogtypeFilledin($con,$CategorieId){
echo "<select name='categorie' class='dropdown form-control'>";
$sql = "SELECT categorieId, categorieNaam
FROM categorie";
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1,$categorieId,$categorieNaam);
while (mysqli_stmt_fetch($stmt1)){
echo "<option value='".$categorieId."'.";
if( $categorieId == $CategorieId){
echo "selected='selected'";
}
echo ">".$categorieNaam."</option>";
}
echo "</select>";
}
Blogedit.php
<?php
require_once '../db/dbControl.php';
require_once '../db/functionControl.php';
session_start();
OpenConnection();
$id = $_SESSION['user'];
?>
// some html up to the while loop
<?php
$a = $_GET['a'];
$sql = "SELECT blog.blogId,
blog.blogTitel,
blog.blogCategorieId,
blog.blogSynopsis,
blog.blogInhoud
FROM blog
WHERE blog.blogId = ? ";
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt1,'i',$a);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1, $blogId, $Titel, $CategorieId, $Synopsis, $Inhoud );
while (mysqli_stmt_fetch($stmt1)){
$Synopsis = str_replace('\r\n','', $Synopsis);
$Inhoud = str_replace('\r\n','', $Inhoud);
?>
// again some HTML
<?php dropdownBlogtypeFilledIn($con,$CategorieId); ?>
// guess what, more html!
<?php
}
?>
Does anyone know how I can solve it? I tried it with the global variable (the OpenConnection() function) but it didn't seem to work.
Edit
I confirm it has indeed to do with the $con variable. I tested it by defining the $con variable again in the function, and it printed perfectly what I wanted. Its a bad solutions. I just prefer to have it defined once.
The weird thing is that it happens only when i put it in a while loop. I have a create form which is exactly the same, except there is no while loop, since I create it all from scratch and there is no PHP involved on that part. I have there a dropdown function as well, which also requires the $con variable, but there it works. I really think it has to do with the while loop.
I solved it for now by creating a new instance of the connection variable before i initiated the prepared statement of the page retrieving the information.
<?php
$connection = $con;
$a = $_GET['a'];
$sql = "SELECT blog.blogId,
blog.blogTitel,
blog.blogCategorieId,
blog.blogSynopsis,
blog.blogInhoud
FROM blog
WHERE blog.blogId = ? ";
mysqli_stmt_init($con);
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt1,'i',$a);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1, $blogId, $Titel, $CategorieId, $Synopsis, $Inhoud );
mysqli_stmt_store_result($stmt1);
while (mysqli_stmt_fetch($stmt1)){
$Synopsis = str_replace('\r\n','', $Synopsis);
$Inhoud = str_replace('\r\n','', $Inhoud);
<?php dropdownBlogtypeFilledIn($connection ,$CategorieId); ?>
?>
With the variable $connection I could initiate the function that required the connection details within the while call. I am not sure if there is a cleaner option here, but indeed I read somewhere that I couldn't use the same connection variable if I am already using it in a prepared statement. Appearantly I cannot ride this one the same connection variable, and that seemed to be the problem. I will look into this and hope I dont have to write a while bunch of connection variables whenever I have multiple dropdowns for example that pull information from the database.
How can you keep track of login status by PHP?
I include the following page to each my page to check the login status. I try to identify the user after he logs in by the cookie.
However, I have not managed to read my login_cookie or use it in any way.
The code handle_login_status.php where I manipulate the login status
<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=masi user=masi password=123");
//1. read the first word in Cookie of the form
//"email#gmail.com,ca05106e445c15197f7213bc12648524
//Then, store this word to $email
$cookie_tripped = explode(",", $_COOKIE['login_cookie']);
$email = $cookie_tripped[0];
$result = pg_prepare($dbconn, "query1", 'SELECT passhash_md5 FROM users
WHERE email = $1;');
$result = pg_execute($dbconn, "query1", array($email));
if(!$result) {
exit;
}
// to take the passhash out of the cookie
$passhash_md5_cookie = $cookie_tripped[1];
if($result == $passhash_md5_cookie) {
$result = pg_prepare($dbconn, "query7", "UPDATE users SET logged_in = $1
WHERE email = $2;");
$result = pg_execute($dbconn, "query7", array("true", $email));
$logged_in = true;
}
else {
$result = pg_execute($dbconn, "query7", array("false", $email));
$logged_in = false;
}
I set up the cookie in the handler of the login form.
The declaration of login_cookie at handle_login_form.php
global $login_cookie;
$login_cookie = $_POST['email'] . ',' . md5($_POST['password']);
$result = pg_prepare($dbconn, "query3", 'SELECT passhash_md5
FROM users WHERE email = $1;');
$result = pg_execute($dbconn, "query3", array($_POST['email']));
while ($row = pg_fetch_row($result)) {
$password_original = $row[0];
}
$login_cookie_original = $_POST['email'] . ',' . md5($password_original);
if ( $login_cookie_original == $login_cookie )
{
setcookie("login_cookie", $login_cookie);
header("Location: /codes/index.php?ask_question");
die("logged in");
}
You don't even give us enough information to debug properly...
Where is $login_cookie_original defined?
Where is $login_cookie defined?
Without that information, we can't debug your code properly. You do use setcookie() properly to set the cookie, and then use the $_COOKIE variable to read it.
Sessions would be an easier way to handle a login situation.
You've also been asking lot of very basic questions about PHP and you don't seem to have a grasp on how the language works. I suggest giving the documentation a good read before your next question.
PHP Documention Home
PHP: Variables From External Sources
You might want to have a look at sessions http://www.tizag.com/phpT/phpsessions.php