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.
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
When execute the query it's not working, it will print error. $q also not coming when i'm print it. but $_SESSION["username"]; is working?
<?php
session_start();
$_SESSION["username"];
include 'Db_Connection.php';
$q= $_GET[q];
$username= $_SESSION[username];
echo $username;
echo $q;
$sql="INSERT INTO search(searcher,searched_time,searched_email)
VALUES ('$username',NOW(),'$q')";
$result = mysqli_query($con,$sql);
if($result)
{
echo "Success";
}
else
{
echo "Error";
}
?>
Couple of things I can pick up from your provided code.
Your second line $_SESSION["username"]; is superfluous as it does nothing
You are using the mysql_* functions which are deprecated
You are not using prepared statements for inserting variables into your query
try something like this:
session_start();
//start assuming this is in your connection file
$con = new mysqli("db-ip-address", "db-user", "db-pass", "db-name")
//end assuming
$q= $_GET[q];
$username= $_SESSION[username];
echo $username;
echo $q;
$sql="INSERT INTO search(searcher,searched_time,searched_email) VALUES (?,NOW(),?)";
$stmt = $con->prepare($sql);
$stmt->bind_param("ss", $username, $q);
$result = $stmt->execute();
if($result) {
echo "Success";
} else {
echo "Error";
}
//remember to cleanup connections etc
as far as the value $q not printing out, make sure that the value is set via the GET query string http://someurl.com/somefile.php?q=some-value and that $q is not some weird non-printable value. If you want to confirm that the value is set, try running var_dump($_GET) to output the contents of your $_GET array to ensure there is actually a value being set.
I believe this is your problem:
$q= $_GET[q];
q should be surrounded in quotes, e.g.:
$q = $_GET['q'];
Other than that, what Damon said was completely correct.
So I can not figure out why this is not adding the content to the DB. I need to add the itemcode and item into the database then be able to read it. This is what i have:
add.php
include('dbconnect.php');
function get_posts() {
$txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
$txtitem = (!empty($_POST['item']) ? $_POST['item'] : null);
$sql1 = "INSERT INTO barcode (itemcode, item) VALUES ('".$txtitemcode."','".$txtitem."')";
if(!mysqli_query($con, $sql1))
{
die('Error:'.mysqli_error());
}
echo "<h1>record added</h1>;
window.location.href='index.php';</script>";
}
mysqli_close($con);
dbconnect.php
$con = mysqli_connect("localhost","root","root","db1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "Connected to Database. Please Continue.";
}
Is anyone able to help?? This is weird to me that it is not working.
It looks like you are calling your insert query from inside of a function yet $con is in the global scope. To include $con within your function you must do this:
include('dbconnect.php');
function get_posts() {
global $con;
$txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
$txtitem = (!empty($_POST['item']) ? $_POST['item'] : null);
$sql1 = "INSERT INTO barcode (itemcode, item) VALUES ('".$txtitemcode."','".$txtitem."')";
if(!mysqli_query($con, $sql1))
{
die('Error:'.mysqli_error());
}
echo "<h1>record added</h1>;
window.location.href='index.php';</script>";
}
get_posts(); // you can call get_posts() here
mysqli_close($con);
Basically, global is a PHP keyword that will allow you to access variables that have been defined in the global scope. Read about in the documentation by clicking here
[..] within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.
And, be sure to call your function, it is as simple as typing the following:
get_posts();
I would like to use custom functions that are all located in one file called functions.php that resides in the includes folder.
A custom function inside functions.php is below and it seems to be working when I remove function nos_check () {} and load up functions.php alone.
function nos_check() {
require_once ('config.php');
mysql_connect($hostname,$dbusername,$dbpassword);
#mysql_select_db($dbname) or die ("Unable to select database");
$sql = mysql_query("SELECT number_of_sites FROM sites WHERE user = '$currentUsername' ");
$row = mysql_fetch_array($sql);
// Assign how many sites the user has into a variable
$how_many = $row['number_of_sites'];
mysql_close();
if ($how_many == 0) {
echo 'You have no sites yet';
} else {
echo 'You have more than one site';
}
}
The file account.php is what's going to call that function:
include "includes/functions.php";
nos_check();
I think I am probably calling the function incorrectly or perhaps I am including the functions file wrong?
SOLUTION:
After hours of messing around and reading more about mysqli etc. I realized that the only problem I actually had was that the script had no idea what $currentUsername was because it was a global variable and functions are not including them automatically in php.
So the error could have been fixed easily by putting global $currentUsername; inside the function nos_check()
Below is a rewritten and hopefully better looking code as well:
function nos_check() {
require 'config.php';
$con = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
global $currentUsername;
$query = "SELECT number_of_sites FROM sites WHERE user = '$currentUsername' ";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
mysqli_free_result($result);
mysqli_close($con);
if ($row[0] == 0) {
echo 'You have no sites yet';
} else {
echo 'You have more than one site';
}
}
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.