Alternative to Using Global Variable in PHP - php

I have developed a function which runs a query and then uses the resulting variables in a logic in another file. I have used global variables to achieve this. I have read global variables are to be avoided, is there another way to write this function to avoid use of global variables.
File 1 (Function File)
<?php
function usertype()
{
include "../classes/sessionstart.php";
include "../config/dbconnect.php";
$user_id = $_SESSION['user_id'];
$select = $con->prepare("SELECT user_usertype, user_gender FROM tbl_user WHERE user_id = $user_id");
$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();
while($data=$select->fetch()){
$GLOBALS['gender'] = $data['user_gender'];
$GLOBALS['usertype'] = $data['user_usertype'];
}
}
?>
File 2 (File Using the Function File)
<?php
usertype();
?>
<div>
<select class="searchpropertyinputs" name="user_usertype" id="user_usertype">
<?php if ($gender == "Male" && $usertype != "Marriage Bureau") { ?> <option value="Bride">Bride</option> <?php } ?>
<?php if ($gender == "Female" && $usertype != "Marriage Bureau") { ?> <option value="Groom">Groom</option> <?php } ?>
<?php if ($usertype == "Marriage Bureau") { ?>
<option value="" hidden>Bride or Groom</option>
<option value="Bride">Bride</option>
<option value="Groom">Groom</option>
<?php } ?>
</select>
</div>

You should return the value from the function:
Updated code, also fixed prepared query, and set an alias for the return columns.
<?php
function usertype()
{
include_once "../classes/sessionstart.php";
include_once "../config/dbconnect.php";
$select = $con->prepare("
SELECT user_usertype as `type`,
user_gender as `gender`
FROM tbl_user
WHERE user_id = :user_id LIMIT 1
");
$select->bindValue(':user_id', (int) $_SESSION['user_id'], PDO::PARAM_INT);
$select->execute();
return $select->fetch(PDO::FETCH_ASSOC);
}
?>
.
<?php
$usertype = usertype();
?>
<div>
<select class="searchpropertyinputs" name="user_usertype" id="user_usertype">
<?php if ($usertype['gender'] == "Male" && $usertype['type'] != "Marriage Bureau") { ?> <option value="Bride">Bride</option> <?php } ?>
<?php if ($usertype['gender'] == "Female" && $usertype['type'] != "Marriage Bureau") { ?> <option value="Groom">Groom</option> <?php } ?>
<?php if ($usertype['type'] == "Marriage Bureau") { ?>
<option value="" hidden>Bride or Groom</option>
<option value="Bride">Bride</option>
<option value="Groom">Groom</option>
<?php } ?>
</select>
</div>
You may also want to move out the includes to connect, session start, or you will have issues for future functions. So that should most likely lead you on to grouping functions into a user class, for example:
<?php
include_once "../classes/sessionstart.php";
include_once "../config/dbconnect.php";
class User {
public function __construct(PDO $con)
{
$this->con = $con;
}
public function type($user_id = 0)
{
$select = $this->con->prepare("
SELECT user_usertype as `type`,
user_gender as `gender`
FROM tbl_user
WHERE user_id = :user_id LIMIT 1
");
$select->bindValue(':user_id', (int) $user_id, PDO::PARAM_INT);
$select->execute();
return $select->fetch(PDO::FETCH_ASSOC);
}
//...
}
$user = new User($con);
$usertype = $user->type($_SESSION['user_id']);
?>

Related

Simple Voting System in PHP

I'm trying to make a simple voting-function to our site. Something in it does not work.
if(isset($_POST['vote']))
{
if($_POST['rate'] == "rate_1")
{
$rate = 'rate_1';
$rate_opload = ++$rest['rate_1'];
}
if else($_POST['rate'] == "rate_2")
{
$rate = 'rate_2';
$rate_opload = ++$rest['rate_2'];
}
if else($_POST['rate'] == "rate_3")
{
$rate = 'rate_3';
$rate_opload = ++$rest['rate_3'];
}
if else($_POST['rate'] == "rate_4")
{
$rate = 'rate_4';
$rate_opload = ++$rest['rate_4'];
}
if else($_POST['rate'] == "rate_5")
{
$rate = 'rate_5';
$rate_opload = ++$rest['rate_5'];
}
$sql = "INSERT INTO kaffe ('{$rate}') VALUES ('{$rate_opload}')";
mysql_query($sql);
}
There are five different columns as you can see because we needed an average in an other part.
I don't know if it's necessary but here is the option-form
<form method=\"post\" id=\"vote\">
<select name=\"rate\">
<option value=\"rate_1\" >★</option>
<option value=\"rate_2\" >★&#x2605</option>
<option value=\"rate_3\" >★★★</option>
<option value=\"rate_4\">★★★★</option>
<option value=\"rate_5\">★★★★★</option>
</select>
<button type=\"submit\" form=\"vote\" value=\"vote\" class=\"fsSubmitButton\">Rösta</button>
First you forgot to put name="vote" into your html form
<form method=\"post\" id=\"vote\">
<select name=\"rate\">
<option value=\"rate_1\" >★</option>
<option value=\"rate_2\" >★&#x2605</option>
<option value=\"rate_3\" >★★★</option>
<option value=\"rate_4\">★★★★</option>
<option value=\"rate_5\">★★★★★</option>
</select>
<button type=\"submit\" name="vote" form=\"vote\" value=\"vote\" class=\"fsSubmitButton\">Rösta</button>
Second it's else if and not if else, your code can be much more compact, nowaday mysql function are deprecated use mysqli
$link = mysqli_connect("localhost", "my_user", "my_password", "world");// Connect to database using mysqli function since mysql function are deprecated
if(isset($_POST['vote']))
{
if($_POST['rate'] == 'rate_1' | $_POST['rate'] == 'rate_2' | $_POST['rate'] == 'rate_3' | $_POST['rate'] == 'rate_4' |$_POST['rate'] == 'rate_5'){
$rate = $_POST['rate'];
$rate_opload = ++$rest[$rate];
$sql = mysqli_prepare($link, "INSERT INTO kaffe ('{$rate}') VALUES (?)");
mysqli_stmt_bind_param($sql , $rate_opload);
mysqli_stmt_execute($sql);
}
}
Your
if(isset($_POST['vote']))
is not reached, you have to add name="vote" to your submit button

Calling method from another php file

So I'm trying my hand at creating php methods from scratch. My classes aren't exactly classes yet, I'm still working on that. Anyway, my issue's I can't seem to get the values I expect from my database. Here's a snippet of my code:
file1.php
<?php function dbConnect() {
$connection = mysqli_connect("localhost", "music_root", "", "music");
if($connection->connect_error) {
return null;
}
return $connection;}
function getCategory() {
$cn = dbConnect();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
return $item["Name"];
}
}
}} ?>
Here's the snippet of how I call the above method in file2.php
<?php ini_set("display_errors", 1);
include_once("file1.php");
$con = dbConnect();
$updateStat = false; ?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<option value="<?php $con->getCategory() ?>"></option>
</select>
</div>
I've tried printing a message at the start of the method to see if the it's being called but the message did not print either so I was wondering, what am I possibly missing here?
I think you have serveral mistakes in your code ... i guess, you don't use OOP (classes) so i modfiy a example which should work .. .if not, please post error messages
file1.php
function getCategory($cn) {
$out = array();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
$out[] = $item["Name"];
}
}
return $out;
}
}
fil2.php
<?php
ini_set("display_errors", 1);
require_once("file1.php");
$con = dbConnect();
$updateStat = false;
$res = getCategory($con);
?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<?php
foreach($res as $cat):
?>
<option value="<?php echo $cat ?>"><?php echo $cat ?></option>
<?php endforeach;?>
</select>

How to create a PHP function that contain a MySQL query?

Hello at the moment I'm using a PHP file called select_Type.php that contain a MySQL query to create a <select></select> Box into HTML. I'm using include_once to link my admin.php and ./Includes/select_Type.php. I already created a file called ./Includes/functions.php where all my querys should be set in PHP functions.
I would like to learn more about functions.
Admin page admin.php where the <select></select> is :
<?php
session_start();
include_once './Includes/functions.php';
CheckLogIn('Superadmin');
SelectType();
//require_once './Includes/select_Type.php';
require_once './Includes/register.php';
?>
select_type.php :
<?php
require_once 'functions.php';
$querySQL = "SELECT * FROM tbltype";
$queryResult = GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)){
$dataArrayType[] = $row;
}
?>
What I tried:
<?php
function SelectType() {
GLOBAL $_POST;
$querySQL = "SELECT * FROM tblType";
$queryResult=GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayType[] = $row;
}
}
?>
What am I doing wrong ?
Thanks in advance :)
Thank you all especially Déjà vu !!!!!
You were all very helpfull.
The problem was, how most of you told me: I didn't returned the value.
Before:
<?php
function SelectType() {
GLOBAL $_POST;
$querySQL = "SELECT * FROM tblType";
$queryResult=GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayType[] = $row;
}
}
?>
Now:
I deleted the GLOBAL $_POST becauce $_POST is already GLOBAL.(Thanks to ɴ ᴀ ᴛ ʜ)
<?php
function SelectType() {
$querySQL = "SELECT * FROM tblType";
$queryResult=GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayType[] = $row;
}
return $dataArrayType;
}
?>
admin.php
I put my function SelectType() in my foreach. Et voila!
<select type="text" id="register_type" name="register_type" required>
<?php
foreach (SelectType() as $row) {
echo "<option value='" . $row['idType'] . "'>" . $row['dtType'] . '</option>';
}
?>
</select>
You can use this:
function sel($table,$field="*", $condition="1",$sort="" ){
if($sort!='') $sort="order by $sort ";
//echo "select $field from $table where $condition $sort ";
$sel_query=mysql_query("select $field from $table where $condition $sort ");
//$sel_result=array();
while($temp_res=#mysql_fetch_array($sel_query))
{
$sel_result[]=$temp_res;
}
return isset($sel_result)?$sel_result: 0;
}
And get result:
$temp_res=sel("post","*"," userid ='".$frnd['friend']."' ORDER BY id DESC");
if($temp_res)foreach($temp_res as $row){
echo $row['content'];
}

select query in view file in codeigniter

This is my simple php html code.
<select id="district" name="district">
<option value="">Select district</option>
<?php
$sql="SELECT * FROM district";
$result = mysqli_query($sql);
while($row = mysqli_fetch_array($result))
{
$district_id = $row['district_id'] ;
$district_name = $row['district_name'];
?>
<option value="<?php echo $district_id;?>"><?php echo $district_name;?></option>
<?php
}
?>
</select>
But it's not working. database is autoloaded.What will be the problem.
you are using direct query not with CI db instance so you will not getting db connection try in CI way
$sql ="SELECT * FROM district";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {?>
<option value="<?php echo $row->district_id;?>"><?php echo $row->district_name;?></option>
<?php }
}
or
$this->db->from('district');
$query = $this->db->get();
if($query->num_rows > 0 ) {
foreach ($query->result() as $row) {
// do your stuff
}
}
Better method to work with MVC framework:- use model for db queries and return data on view via controller (do not use direct query on view)
May be your get CI instance wirte you CI query directly
$CI =& get_instance();
$CI->load->model('modelname');
$result = $CI->modelname->functionname();
If you must access db directly from, view try this:
$this->load->view('view_name',["db"=>$this->db,"other_data=>"data"]);
//$this->db //CI db instance
In view you can now do:
$db->query("select * from table")->result();
please try this
<select id="district" name="district">
<option value="">Select district</option>
$result = mysqli_query($sql);
while($row = $result->fetch_array())
{
$district_id = $row['district_id'] ;
$district_name = $row['district_name'];
?>
<option value="<?php echo $district_id;?>"><?php echo $district_name;?></option>
<?php } ?>

Issue with Php And utf8 inserting to mysql [duplicate]

This question already has answers here:
Issue with PHP MySQL and insert into UTF-8 [closed]
(3 answers)
Closed 10 years ago.
I have a problem with php & mysql, insert to database using utf-8.
first file:
addsite:
<?php
include 'header.php';
if(isset($data)) {
foreach($_POST as $key => $value) {
$posts[$key] = filter($value);
}
if(isset($posts['type'])){
if($posts['url'] == "http://" || $posts['url'] == ""){
$error = "Add your page link!";
}else if($posts['title'] == ""){
$error = "Add your page title!";
}else if(!preg_match("/\bhttp\b/i", $posts['url'])){
$error = "URL must contain http://";
}else if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $posts['url'])){
$error = "Please do not use special characters in the url.<";
}else{
include "plugins/" . $posts['type'] . "/addsite.php";
}
}
?>
<div class="contentbox">
<font size="2">
<li>Pick the type of exchange you are promoting from the dropdown menu.</li>
<li>Set the amount of coins you wish to give per user complete(CPC).</li>
<li>The higher the amount of coins the higher the Links position.</li>
</div>
<div class="contentbox">
<div class="head">Add Site</div>
<div class="contentinside">
<?php if(isset($error)) { ?>
<div class="error">ERROR: <?php echo $error; ?></div>
<?php }
if(isset($success)) { ?>
<div class="success">SUCCESS: <?php echo $success; ?></div>
<?php }
if(isset($warning)) { ?>
<div class="warning">WARNING: <?php echo $warning; ?></div>
<?php } ?>
<form class="contentform" method="post">
Type<br/>
<select name="type"><?php $select = hook_filter('add_site_select', ""); echo $select; ?></select><br/><br/>
Link<br/>
<input name="url" type="text" value="<?php if(isset($posts["url"])) { echo $posts["url"]; } ?>"/><br/><br/>
Title<br/>
<input name="title" type="text" value="<?php if(isset($posts["title"])) { echo $posts["title"]; } ?>"/><br/><br/>
Cost Per Click<br/>
<?php if($data->premium > 0) { ?>
<select name="cpc"><?php for($x = 2; $x <= $site->premcpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php }else{ ?>
<select name="cpc"><?php for($x = 2; $x <= $site->cpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php } ?>
<input style="width:40%;" type="Submit"/>
</form>
</div>
</div>
<?php
}
else
{
echo "Please login to view this page!";
}
include 'footer.php';
?>
second file , plugin addsite.php
<?php
$num1 = mysql_query("SELECT * FROM `facebook` WHERE `url`='{$posts['url']}'");
$num = mysql_num_rows($num1);
if($num > 0){
$error = "Page already added!";
}else if(!strstr($posts['url'], 'facebook.com')) {
$error = "Incorrect URL! You must include 'facebook.com'";
}else{
mysql_query($qry);
mysql_query("INSERT INTO `facebook` (user, url, title, cpc) VALUES('{$data->id}', '{$posts['url']}', '{$posts['title']}', '{$posts['cpc']}') ");
$success = "Page added successfully!";
}
?>
when i write arabic language in the form and submit ,
it went to database with unkown language like :
أسÙ
database collaction : utf8_general_ci
<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');
$host = "localhost"; // your mysql server address
$user = "z*******"; // your mysql username
$pass = "m********"; // your mysql password
$tablename = "z*******"; // your mysql table
session_start();
$data = null;
if(!(#mysql_connect("$host","$user","$pass") && #mysql_select_db("$tablename"))) {
?>
<html>
MSQL ERROR
<?
exit;
}
include_once 'functions.php';
require_once "includes/pluggable.php";
foreach( glob("plugins/*/index.php") as $plugin) {
require_once($plugin);
}
hook_action('initialize');
$site = mysql_fetch_object(mysql_query("SELECT * FROM settings"));
?>
after removing
$posts[$key] = filter($value); "
from header.php
The output shift from:
To:
& Oslash; & pound; & Oslash; ³& Ugrave
to : Ù Ù Ù
header file : http://zwdha.com/header.txt
You might need to add some ini_set statements if your db is full utf8: http://www.polak.ro/php-mysql-utf-8.html
This a very basic insert query to see if you can insert data in you database with PHP.
<?php
function inserting_data() {
$host = "host";
$user = "username";
$password = "password";
$database = "database";
$charset = "utf8";
$link = mysqli_connect($host, $user, $password, $database);
mysql_set_charset($charset, $link);
IF (!$link) {
echo('Unable to connect to the database!');
} ELSE {
/*
* this just to test if something gets inserted into your table.
* If some of your columns are set to not null you should add them tot this insert query.
*/
$query = "INSERT INTO facebook (`title`) VALUES('test_title'), ('test_title1')";
mysqli_query($link, $query);
}
mysqli_close($link);
}
?>
This is a very basic select query to retrieve data form your database.
<?php
function selecting_data(){
$host = "host";
$user = "username";
$password = "password";
$database = "database";
$charset = "utf8";
$link = mysqli_connect($host, $user, $password, $database);
mysql_set_charset($charset, $link);
IF (!$link) {
echo('Unable to connect to the database!');
} ELSE {
/*
* this just to test if something gets returned from your table.
*/
$query = "SELECT * FROM facebook";
$result = mysqli_query($link, $query);
while ($rows = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $rows['title'];
}
}
mysqli_close($link);
}
?>
My advise is to first test if you can get data in your database and retrieve it. By trial and error you will need to solve your question. B.T.W. I have used MYSQLI_ function instead of MYSQL. The mysql_ functions will depreciate soon. Hope this helps.
a - you should not use mysql_ functions. use PDO. this error is one of the reasons.
b - mysql_set_charset('utf8');
c - are the columns you are trying insert data using utf8_general_ci ?
d - on my.cf set default-character-set and character-set-server
if this doesn't work read this:
http://www.oreillynet.com/onlamp/blog/2006/01/turning_mysql_data_in_latin1_t.html
and this:
http://www.phpwact.org/php/i18n/utf-8
if after that you still dont get it right, make sure to listen to people and use PDO.

Categories