Proper way to call a custom php function from another file - php

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';
}
}

Related

$_post isset not working. Used the same syntax on other examples and works perfectly. Value not able to be posted for where claus MYSQL PHP

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

accessing connection variable in a while loop

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.

mysqli and global variable

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.

Having problems with cannot redeclare

I just finished writing this script and getting it to work but I need to use it a total of 8 times on 1 page. It works fine the first time but the second time I get: Fatal Error cannot redeclare get_names(). I've been told the way around this is to use include_once but I can't seem to figure out how exactly I'm supposed to do that. I've tried cutting both of the get_names parts out of the code and putting them into separate php files then using the include_once command. I got it to work but once again I got the same error after trying to use the script twice. I also tried putting the whole script into a php file and then using the include_once("scriptname.php") command and the same thing happened. So my questiion is how exactly do I cut this script up so I don't get this error anymore?
<?php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row['pool'] % 2) {
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach($names as $name) {
echo $name . "<br/>";
}
} else {
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach($names as $name) {
echo $name . "<br/>";
}
}
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
} ?>
put getNames function in afile.php and include that once at the start. take getNames function out of your current file.
so things goes like this
in first php file (say) you have this code - filea.php
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
}
you second file will have fileb.php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
..... rest of source code excluded. Make sure you get rid of getNames in this file
Now just include as per normal
include 'filea.php'; // include it once only
include 'fileb.php'; // as many times as your wish
or just wrap your code in a function and call that instead
If you are using this script 8 times, then put the entire thing inside a function and call that function 8 times instead of copy pasting.

Page including with mysql in php

I have a nice page including system here is the code for it
if(isset($HTTP_GET_VARS['mod']))
{
$page = $HTTP_GET_VARS['mod'];
}
else
{
$page = 'home';
}
switch($page)
{
case 'home':
require('home.php');
break;
default:
echo('Error: There is no file on this server with that name');
}
}
I am trying to get the case, require from a DB called pages there are 2 fields Name, Link i am trying to get all of the results from the table so it will display the pages
It's not particularly clear from your question, but my reading of it is that you want a way to check any value of $page against a link value in a db table (pages?), without having to write all possible values in to your switch statement,
If my understanding is correct, then the below is a quick-and-dirty function which should let you do this. In a live, heavily-trafficed environment you'd obviously need to build in caching so every page load doesn't hit the db, and strong input validation, neither of which are in the demo below, but this should at least give you an idea of where to go next.
Common library file:
/**
* Given a page name, see if we have an associated
* link in the db.
* If so, return the link value, else false
*/
function getTemplate($page)
{
// Check db to see if we have a link for this page
// On heavy-traffic sites, this should be cached out
$query = sprintf("SELECT link FROM pages WHERE name = '%s'",
mysql_real_escape_string($page));
$result = mysql_query($query, $db_cnx);
// Have we any results?
if (mysql_num_rows($result) > 0)
{
// Assumption: 'name' is unique in the db
$row = mysql_fetch_assoc($result);
return $row['link'];
}
else
{
return false;
}
}
Header.php:
include('common.lib.php');
if(isset($HTTP_GET_VARS['mod']))
{
$page = $HTTP_GET_VARS['mod'];
}
else
{
$page = 'home';
}
// Check whether our page has a link in the db
$template = get_template($page);
if($template)
{
require( $template );
}
else
{
// Got false back from get_template, no link found
echo('Error: There is no file on this server with that name');
}
$server_db = "YOUR_SERVER_DB";
$user_db = "YOUR_USER_DB";
$password_db = "YOUR_PASSWORD_DB";
$db_name = "YOUR_DB_NAME";
$table = "YOUR_TABLE_NAME";
$link = mysql_connect($server_db,$user_db,$password_db);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_name);
$sql = sprintf("select Name, Link from %s",$table);
$rs = mysql_query($sql,$link);
while($row = mysql_fetch_assoc($rs)) {
echo "<a href='".$row['Link']."'>".$row['Name']."</a>";
}
mysql_free_result($rs);
mysql_close($link);

Categories