error in calling same function twice in php - php

I have a function named record_list() which helps me echo fetched query from database every time I refresh/visit a page. I tried to use this function by echoing it twice but unfortunately all my DOM elements after the script get hidden and I can't use the following divisions/lists in my HTML. But if I call it once it's working fine without any problem.
Apart form this I am getting this error:
Fatal error: Call to a member function query() on a non-object
record_list():
function record_list(){
//include db configuration file
include_once("configuration.php");
try{
//MySQL query
$user_id = $_SESSION['user_id'];
$results = $mysqli->query("SELECT * FROM education_record WHERE user_id='$user_id' ");
//get all records from add_delete_record table
while($row = $results->fetch_assoc())
{
echo '<li class = "col-md-4 col-xs-12 records_display" id="item_'.$row["id"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_btn" id="del-'.$row["id"].'">';
echo '<img src="../img/removeButtonIcon.svg" height ="20px" width ="20px" border="0" />';
echo '</a></div>';
echo '<div class="controls group_row">';
echo '<div class="controls group">';
echo '<input disabled type="text"class="group"style="width:175px" value ="'.$row["degree_name"].'"/>';
echo '<input disabled type="text"class="group"style="width:175px" value ="'.$row["institute"].'"/>';
echo '<input disabled type="text"class="group"style="width:175px" value ="'.$row["specialisation"].'"/>';
echo '<input disabled type="text"class="group"style="width:100px" value ="'.$row["date_of_passing"].'"/>';
echo '</div>';
echo '</div>';
echo '</li>';
}
}
catch (mysqli_sql_exception $e) {
throw $e;
die();
}
$mysqli->close();
//close db connection
}
configuration.php:
<?php
$host = 'localhost';
$dbname = 'databasename';
$username = 'username';
$password = 'can-be-anything';
try {
$mysqli = new mysqli($host, $username, $password, $dbname);
} catch (mysqli_sql_exception $e) {
throw $e;
die();
}
?>
Please help me identifying this error.

This is because you have to use include("configuration.php"); not include_once("configuration.php"); If you include_once, it will only work when the first instance of this configuration file is included in the script somewhere.
I would suggest making a class to wrap your connection saving it to a singleton state for use everywhere else in your script. Here is a simple example:
classes/class.DatabaseConfig.php
<?php
class DatabaseConfig
{
private static $singleton;
public function __construct()
{
if(empty(self::$singleton))
self::$singleton = $this;
return self::$singleton;
}
public function connect($host = "localhost", $username = "username", $password = "password", $database = "database")
{
// Create connection
try {
$mysqli = new mysqli($host, $username, $password, $database);
return $mysqli;
} catch (mysqli_sql_exception $e) {
throw $e;
die();
}
}
}
classes/class.Db.php
<?php
class Db
{
private static $singleton;
public static function mysqli()
{
if(empty(self::$singleton)) {
$con = new DatabaseConfig();
self::$singleton = $con->connect();
}
return self::$singleton;
}
}
index.php
<?php
// Look into using spl_autoload_register() here
include_once("classes/class.DatabaseConfig.php");
include_once("classes/class.Db.php");
// This will work
$con = Db::mysqli();
function myQuery()
{
// This will also work, so long as you have included the class
// file once before this function (not necessarily in this function either)
// is called to use
$con = Db::mysqli();
}

This happens because you close connection with $mysqli->close(); every time function is executed but, as #Rasclatt suggested, you open connection only once with include_once directive. You may replace include_once with include or try #Rasclatt OOP approach but if you don't want to dive into OOP for some reason I suggest to separate connection operation from the function and pass it to the function as a parameter like this
include_once("configuration.php");
function record_list($mysqli){
try{
//MySQL query
$user_id = $_SESSION['user_id'];
$results = $mysqli->query("SELECT * FROM education_record WHERE user_id='$user_id' ");
//get all records from add_delete_record table
while($row = $results->fetch_assoc())
{
echo '<li class = "col-md-4 col-xs-12 records_display" id="item_'.$row["id"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_btn" id="del-'.$row["id"].'">';
echo '<img src="../img/removeButtonIcon.svg" height ="20px" width ="20px" border="0" />';
echo '</a></div>';
echo '<div class="controls group_row">';
echo '<div class="controls group">';
echo '<input disabled type="text"class="group"style="width:175px" value ="'.$row["degree_name"].'"/>';
echo '<input disabled type="text"class="group"style="width:175px" value ="'.$row["institute"].'"/>';
echo '<input disabled type="text"class="group"style="width:175px" value ="'.$row["specialisation"].'"/>';
echo '<input disabled type="text"class="group"style="width:100px" value ="'.$row["date_of_passing"].'"/>';
echo '</div>';
echo '</div>';
echo '</li>';
}
}
catch (mysqli_sql_exception $e) {
throw $e;
die();
}
}
/// You may call here record_list($mysqli) function as many times as you wish
record_list($mysqli)
$mysqli->close();
//close db connection

Related

I cannot figure out why DeleteTask.php does not work, yet RetrieveTask.php does

I cannot for the life of me figure out why the DeleteTask function will not work, when it is almost the same as RetrieveTask; only called in different files.
Now:
src/controller/RetrieveTask:
prepares a PDO database query, and passes it to src/view/DisplayTask.php, which uses a for each-loop to echo the rows and an <a> element linking to src/redir/DeleteAndReturn.php.
This file simply executes src/controller/DeleteTask.php and src/controller/ReturnToIndex.php.
The file code and order is as follows:
RetrieveTask
<?php
function RetrieveTask($db)
{
$sql = 'SELECT * FROM task';
return $db->query($sql);
}
?>
Which gets passed to DisplayTask:
<?php
function DisplayTask($db)
{
foreach (RetrieveTask($db) as $row)
{
echo "<li>" . $row['tsk-name'] . "<br>" . $row['tsk-desc'] . "<a id=".$row['id']." class='btn btn-danger' href='/todo/redir/DeleteAndReturn.php'>Delete</a>" . "</li>";
}
}
?>
Which get passed to index.php in the /todo/home directory. All I need to do is call DisplayTask($DbHandler) Where $DbHandler is an instant of the db class.
Now for src/controller/DeleteTask.php:
<?php
function DeleteTask($db)
{
echo "Delete";
$sql = ' DELETE FROM task where id= 2 ';
return $db->query($sql);
}
?>
and src/controller/ReturnToIndex.php:
<?php
function ReturnToIndex()
{
header('Location: /todo/home');
}
?>
Leads to redir/DeleteAndReturn.php
<?php
include_once('../src/model/db/DbConnect.php');
include_once('../src/controller/DeleteTask.php');
include_once('../src/controller/ReturnToIndex.php');
$DbHandler = new DbConnect();
DeleteTask($DbHandler);
$DbHandler->CloseConnection();
ReturnToIndex();
?>
I've tried passing the item id as a get parameter in a query string. Deleting all tables. Manually selecting the id. I can't get it to work. Any help would be much appreciated. I googled and looked up documentation for hours. I feel like it is something exceedingly simple that just went way over my head.
Full code is here: https://github.com/liengesbor.
As maxim_039 suggested, I changed how a variable array was passed to the DB construct. Somehow this fixed the issue.
function __construct()
{
- parent::__construct('mysql:host=localhost;dbname=todo;', 'root', 'alexel', array ('$opt'));
+ parent::__construct('mysql:host=localhost;dbname=todo;', 'root', 'alexel', $this->opt);
echo "Connected to Database";
}
Here is the database code:
<?php
// Connect to the database using PDO and MySQL
class DbConnect extends PDO
{
protected $dsn = "mysql:host=localhost;dbname=todo;";
protected $dbPassword = 'alexel';
protected $dbUsrName = 'root';
protected $opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
function __construct()
{
parent::__construct('mysql:host=localhost;dbname=todo;', 'root', 'alexel', $this->opt);
echo "Connected to Database";
}
function CloseConnection()
{
$this->DbConnection = null;
}
}
?>

why is my class not working? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Guys i'm scratching my head for this problem. As, i get this error from my openshift log
PHP Fatal error: Call to a member function totalids() on a
non-object in
/var/lib/openshift/573dc0da2d5271d357000294/app-root/runtime/repo/st&com.php
on line 46, referer: http://express-pad4u.rhcloud.com/
And doing var_dump on $conn and $project from dbconfig.inc.php file in st&com.php gives the following message:
object(PDO)#1 (0) { } object(projecteg)#2 (4) {
["_db":"projecteg":private]=> object(PDO)#1 (0) { } ["query"]=> NULL
["stmth"]=> NULL ["conn"]=> NULL }
here is my dbconfig.inc.php code:
session_start();
define('DB_HOST', getenv('OPENSHIFT_MYSQL_DB_HOST') . ':' . getenv('OPENSHIFT_MYSQL_DB_PORT'));
define('DB_USER', getenv('**********'));
define('DB_PASS', getenv('**********'));
define('DB_BASE', 'project');
define('DB_PORT', getenv('OPENSHIFT_MYSQL_DB_PORT'));
try {
$conn = new PDO("mysql:host=" . getenv('OPENSHIFT_MYSQL_DB_HOST') . ";dbname=" . DB_BASE . "", "********", "*********");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $exc) {
echo $exc->getMessage();
}
include 'classes.inc.php';
$project = new projecteg($conn);
here is the code for st&com.php file:
<?php
//error_reporting(0);
include_once "includes/dbconfig.inc.php";
$status_replies="";
$status_list="";
$statusui_edit="";
$isowner="";
$is_friend="";
$statusdeletebutton='';
$reply_delete_button="";
$load= (int)($_POST['load'])*2;
var_dump($conn);
echo '<br>';
var_dump($project);
echo '<br>';
function hashtags($dat) {
$regex="/#+([a-zA-z0-9._-]+)/";
$dat1= preg_replace($regex, '$0', $dat);
return $dat1;
}
function taggingsys($dat) {
$regex="/#+([a-zA-z0-9!._-]+)/";
$dat1= preg_replace($regex, '$0', $dat);
return $dat1;
}
function ff(&$s) {
//$conn="";
//require_once 'includes/dbconfig.inc.php';
$output=array();
// $friends=array();
//$project= new \projecteg($conn);
// $totalids=array();
$verify_friend=array();
foreach ($s as $i=> $r ){
//array_push($friends, $r);
$r["friend_one"] == $_SESSION['uname'] ? $friends[]= $r["friend_two"] : $friends[] = $r["friend_one"];
echo '<pre>';var_dump($friends);echo '</pre>';
$verify_friend= $project->totalids($friends[$i]);
/* foreach ($friends as $v) {
echo '<br><h1>'; print_r($v); echo '</h1></br>';
echo '<br>';
// var_dump($verify_friend);
// array_push($totalids, $verify_friend);
}
echo '<pre>'; var_dump($verify_friend); echo '</pre>'; */
array_push($output, $verify_friend);
}
return $output;
}
$f = array();
$stmt= $conn->prepare("select friend_one, friend_two from friends where (friend_one=:session OR friend_two=:session) and accepted='1'");
$stmt->bindparam(":session",$_SESSION['uname']);
$stmt->execute();
$f=$stmt->fetchAll();
$ids= ff($f);
foreach ($ids as $i=>$v){
$id=$v[$i]['user_id'];
//fetch user_id from update table in db and inject it to the feed query.
$totalUpdates=$project->totalUpdates1($id,$load);
$total_sess_count=$project->totalupdatescount($id);
foreach ($totalUpdates as $j=>$row1) {
$updateid=$row1['update_id'];
$account_name=$row1['account_name'];
$u_id=$row1['user_id_u'];
$author=$row1['author'];
$post_date=$row1['time'];
$title= stripslashes($row1['title']);
$data= stripslashes($row1['update_body']);
$data1= hashtags($data);
//$data1= taggingsys($data0);
$pic=$project->viewByUname($author);
$uid=$pic['user_id'];
$datemade = strftime("%B %d", strtotime($post_date));
$avatar=$pic['avatar'];
if ($avatar!=""){
$feed_pic='user/'.$uid.'/'.$avatar;
} else {
$feed_pic='img/avatardefault.png';
}
//other lengthy logic
here is the class logic:
<?php
class projecteg
{
private $_db;
public $query;
public $stmth;
public $conn;
public function __construct($conn)
{
$this->_db = $conn;
}
public function totalids($friend)
{
try {
$sql2 = "select user_id from user where uname=:session or uname=:friend and activated='1'";
$stmth = $this->_db->prepare("$sql2");//Check here syntax of $db
$stmth->bindValue(":session", $_SESSION['uname']);
$stmth->bindValue(":friend", $friend);
$stmth->execute();
return $stmth->fetchAll();
} catch(PDOException $exc) {
echo $exc->getMessage();
}
}
}
how do i make my method and conn to work.
You are trying to use $project inside a function ff() without passing it in or declaring it inside the function so it doesn't exist inside the scope of that function. Do some research on scope that should help you out. But for now you need to pass in $project to ff() if you want to use it. Something like this:
function ff(&$s,$project) {
...
}
$ids = ff($f,$project);
That is assuming you want to use the $project you have already declared. If not you will need to create a new instance inside the function like Patrick-Q said in the comments.

add checkbox with values from query

i'm trying to create a php web app that will have options to select using checkbox form and then submit the checkedbox to other file. but how can i do this if the value of checkbox is defined with values from query?
please help me, i cant find a solution :/
<form action="addPratosEnc4.php" method="POST">
*Pratos a Adicionar:
<select name="nomeA">
<?php
try
{
$host = "xxxx";
$user ="xxx";
$password = "xxx";
$dbname = $user;
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT nomeA FROM Disponivel;";
$result = $db->query($sql);
foreach($result as $row)
{
$nomeA = $row['nomeA'];
/*should be here?*/
}
$db = null;
}
catch (PDOException $e)
{
echo("<p>ERROR: {$e->getMessage()}</p>");
}
?>
</select>
<br>
<br>
<input type="submit" value="Disponibilizar">
</form>
Ok, let's get this straight
You want checkboxes, right! I mean, check!
The nameA column is unique or primary, no duplicates!
the logic and template together
<?php
try {
$host = "xxxx";
$user ="xxx";
$password = "xxx";
$dbname = $user;
$db = new PDO("mysql:host=$host;dbname=$dbname",$user,$password);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$q = "SELECT nomeA FROM Disponivel";
$options = array();
$count = 0;
foreach($db->query($q) as $row) {
$count++;
$options[$row['nomeA']] = '<input type="checkbox" name="dispo[]" value="'.$row['nomeA'].'" />';
}
echo '<p>Rows processed: '.$count.'</p>';
$db = null;
} catch (PDOException $e) {
echo '<p>ERROR: '.$e->getMessage().'</p>';
}
?>
<form action="addPratosEnc4.php" method="POST">
*Pratos a Adicionar:
<?php
if (!$options) echo ' agora no hay pratos';
else foreach ($options as $name => $input) echo '<label>'.$input.' '.$name.'</label><br />';
?>
<br />
<br />
<button type="submit">Disponibilizar</button>
</form>
Try this, ask any questions if you have them and if any solutions worked for you, please mark them as answer
To render the option list you do:
.......
$nomeA = $row['nomeA'];
/*should be here?*/
?> <option value="<?php echo $nomeA; ?>"><?php echo $nomeA; ?></option><?php
}
$db = null;
}
........
This should create a option list within the select that is filled with the results from the query. I assume you meant an option list not checkboxes -
A select box gives you each option and you can only select 1. You could also do this with radiobuttons. On the other hand you may have meant to use Checkbox's where the user can select multiple boxes.
In this case you shouldnt wrap anything in the select just something like
<input type="checkbox" name="group" value="<?php echo $nomeA; ?>">I have a <?php echo $nomeA; ?><br>
within the for loop.
Good Luck
Narimm
echo'<input type ="checkbox" name = "'.$row['nomeA'].'"value = "'.$row['nomeA'].'" />'.$row['nomeA'].'<br />;
instead of :
$nomeA = $row['nomeA'];
remove the select tag and that should work.
just to complete my task, i will post what its need to get the values selected:
<?php
session_start();
$email = $_SESSION['email'];
$nEnc = $_SESSION['nEnc'];
$options = $_REQUEST['dispo'];
echo("<p>$email</p>");
echo("<p>$nEnc</p>");
try
{
$host = "xxxx";
$user ="xxxx";
$password = "xxxx";
$dbname = $user;
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach($options as $name){
$nomeA = $name;
$sql = "INSERT INTO RegistoEnc VALUES ('$email',$nEnc,'$nomeA');";
echo("<p>$sql</p>");
$db->query($sql);
};
$db = null;
}
catch (PDOException $e)
{
echo("<p>ERROR: {$e->getMessage()}</p>");
}
echo "<br>Encomenda Criada!!<br>";
?>

PHP certain part of code is not executing

Hi I am facing a unique issue with my PHP script.Here is my code. After writeToDB() is executed I dont see the echo ("<script> top.location.href=www.facebook.com</script>");
Can someone let me know why my script stops executing after writing to db?
<?php
function writeToDB($access_token,$uid,$username,$birthday,$gender,$age)
{
/* Database Connection */
$user = "xxxx";
$password = "xxxx";
$host = "xxxxxxxxxxxxxxxxxx";
//connect to database, where tsnames.ora is setup
$connect_obj = oci_connect($user, $password, $host);
if ($connect_obj) {
error_log("connected okay");
} else {
$err = OCIError();
echo "Oracle connection error " . $err[text];
return;
}
$select_query = "SELECT USER_ID FROM FBTABLE WHERE USER_ID= '$uid'";
$select_sql_stmt = oci_parse($connect_obj, $select_query);
//execute statement
try {
$r = oci_execute($select_sql_stmt, OCI_DEFAULT);
if (!$r) {
$p = oci_error($select_sql_stmt);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
$user_id_in_db = null;
while (oci_fetch($select_sql_stmt)) {
$user_id_in_db = oci_result($select_sql_stmt, 'USER_ID');
}
// User already exists in db so update instead of insert
if ($user_id_in_db != null) {
$query ="UPDATE FBTABLE SET ACCESS_TOKEN='$access_token' WHERE USER_ID='$uid'";
} else {
$query = "INSERT INTO FBTABLE(ACCESS_TOKEN, USER_ID,USER_NAME,BIRTHDAY,GENDER,AGE)
VALUES
('$access_token','$uid','$username','$birthday','$gender','$age')";
}
//create sql statement
$sql_statement = oci_parse($connect_obj, $query);
//execute statement
try {
$r = oci_execute($sql_statement, OCI_DEFAULT);
if (!$r) {
$p = oci_error($sql_statement);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
//Commit transaction
$committed = oci_commit($connect_obj);
//Test whether commit was successful. If error occurred, return error message
if (!$committed) {
$error = oci_error($conn);
echo 'Commit failed. Oracle reports: ' . $error['message'];
}
//close the connection
$oci_free_statement($sql_statement);
if (oci_close($connect_obj)) {
echo " oci connection not closed!!!";
}
//close the connection
$oci_free_statement($sql_statement);
}
?>
<html>
<body>
<?php
$access_token = $_GET['access_token'];
$uid = $_GET['uid'];
$username = $_GET['username'];
$birthday = $_GET['birthday'];
$gender = $_GET['gender'];
$age = $_GET['age'];
echo $username;
writeToDB($access_token,$uid,$username,$birthday,$gender,$age);
echo ("<script> top.location.href=www.facebook.com</script>");
?>
</body>
</html>
i think error is in $oci_free_statement($sql_statement); must be oci_free_statement($sql_statement); extra $ before oci_free_statement
http://php.net/manual/en/function.oci-free-statement.php
no any error show because of error_display is off
Your JavaScript code should be
echo ("<script> top.location.href='http://www.facebook.com';</script>");
It's happen because writeToDB() causes error. You don't see this error because error_display is off or error_reporting = 0
Also maybe you didn't install OCI8. So when you call oci_connect it will cause error.
Thanks.
you are not using quotes around the string:
www.facebook.com should be 'www.facebook.com'

PHP Class Function Ignores Return Statement

For some reason the return doesn't work when the check_em() succeeds. I'm new to php, so I'm at a loss here.
<?php
//Class to handle mysql
class db_handler {
private $db_host = 'localhost';
private $db_name = 'project';
private $db_user = 'project';
private $db_pass = 'dbpassword';
private $db_con_mysql = '';
private $db_con_db = '';
public function check_em($username, $password) {
$db_query = "SELECT password FROM user WHERE name='".$username."' LIMIT 1;";
if($this->db_con_mysql!='') {
$db_query_response = mysql_query($db_query) or die('Query failed: '.mysql_error());
$db_query_return = mysql_fetch_row($db_query_response);
$db_sha1_hash = $db_query_return[0];
echo $db_sha1_hash."<br>";
echo sha1($password)."<br>";
if(sha1($password)==$db_sha1_hash) {
return 'user valid'; //THIS DOESN'T WORK!?!?!?
} else {
return 'no good';
}
} else {
$this->db_connect();
$this->check_em($username, $password);
}
}
//Connect to mysql, then database
private function db_connect() {
$this->db_con_mysql = mysql_connect($this->db_host, $this->db_user, $this->db_pass) || die('Connection failed: '.mysql_error());
$this->db_con_db = mysql_select_db($this->db_name) || die('Could not use'.$this->db_name.'. '.mysql_error());
return;
}
//Disconnect from database and reset vars used to track connection.
private function db_disconnect() {
if($this->db_con_mysql!='') {
mysql_close();
$this->db_con_mysql = '';
$this->db_con_db = '';
return;
}
}
public function fake($some_val) {
if($some_val<6) {
return TRUE;
} else {
return FALSE;
}
}
}
$db_obj = new db_handler();
$val1 = $db_obj->check_em('someuser','password'); //should return 'user valid'
echo "val1:".$val1."<br>";
echo "<br><br>";
$val2 = $db_obj->check_em('someuser','passw0rd'); //should return 'no good'
echo "val2:".$val2."<br>";
echo "<br><br>";
echo "test<br>";
echo $db_obj->fake(4)."<br>";
?>
Results:
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
val1:
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
7c6a61c68ef8b9b6b061b28c348bc1ed7921cb53
val2:no good
test
1
This line needs a return:
return $this->check_em($username, $password);
But a more sensible solution would be to connect to the database inside the if when the connection is null. Really, the whole thing could be better written, but I'll leave it at that.
...
else {
$this->db_connect();
return $this->check_em($username, $password);
}
...
You want to add the return, so that if it fails, then it goes one level deeper and finds another. If that level deeper succeeds, it passes the value up to the level above, which can pass it up and up until it reaches the original function call.

Categories