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.
Related
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 4 years ago.
I want to show all the records from the DB on my website, it's a PDO built website. I want it to show all the records so you can see what's in the DB.
This is how my DB looks like
The connection is set up in a different document called config.php
<?php
date_default_timezone_set('Europe/Amsterdam');
error_reporting(E_ALL & ~ E_DEPRECATED);
ini_set('display_errors', 'ON');
$CONFIG = array();
$CONFIG['root'] = '/home/tom/public_html';
$CONFIG['rootwebsite'] = '/home/tom/public_html';
$CONFIG['website'] = 'https://###';
$CONFIG['dbhost'] = 'localhost';
$CONFIG['dbuser'] = '####';
$CONFIG['dbpass'] = '####';
$CONFIG['dbdatabase'] = 'tom';
?>
This is the code I have in a php document and tried using. The problem is it won't show anything on my website (this is a different file than the file my website is):
<?php
class Forum {
private $dbh; //dbh = database handler.
public function __construct($database) {
$this->dbh = $database;
}
public function getForum() {
$getTopic = $dbh->prepare("SELECT * FROM topics ORDER BY id DESC");
$getTopic->execute();
$topics = $getUTopic->fetchAll();
foreach ($topics as $topic) {
echo $topic['onderwerp'] . '<br />';
}
}
}
You are not calling the right $connection variable. It should be $this->dbh
$getTopic = $this->dbh->prepare("SELECT * FROM topics ORDER BY id DESC");
Also you are mixing the variables after execute(). You should use easy to remember variables.
public function getForum() {
try {
$getTopic = $this->dbh->prepare("SELECT * FROM topics ORDER BY id DESC");
$getTopic->execute();
$topics = $getTopic->fetchAll();
foreach ($topics as $topic) {
echo $topic['onderwerp'] . '<br />';
}
} catch (PDOException $pdoEx) {
echo $pdoEx->getMessage();
exit;
} catch (Exception $ex) {
echo $ex->getMessage();
exit;
}
}
Also since you are not passing any variable to your query, there is no point of using prepare(). Just call query() instead.
For error reporting add,
error_reporting(E_ALL); #place at the top of the script
Also you should consider using a proper IDE like PHPstorm or Netbeans, as they would easily point out unsed variables
As suggested by #adpro, here is a link, to help with debugging
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;
}
}
?>
I am working on a class where I want to check if everything is filled in and if everything is filled in then insert into the database, but I am stuck on how I can insert within my class so I hope you guys could help me. I never got any errors of this problem.
Here is the code:
<?php
class clsCatCheck
{
private $catName;
public function __construct($catName)
{
$this->setCatName($catName);
}
public function setCatName($catName)
{
$connect = new PDO('mysql:host=hostname;dbname=dbname', "username", "password");
$select = $connect->prepare('SELECT * FROM category');
$row = $select->fetch();
if (isset($_POST['addCat'])) {
if (empty($_POST['catName'])) {
throw new Exception('Geen categorienaam is ingevuld<br />');
}
//if (strlen($_POST['catName'] <= 4)) {
// throw new Exception('De categorienaam moet minimaal 4 letters of langer zijn<br />');
//}
if ($_POST['catName'] == $row[1]) {
throw new Exception('Deze categorienaam bestaat al<br />');
}
}
else {
$query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName = catName)");
$query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);
$query->execute();
}
$this->catName = $catName;
}
public function getCatName()
{
return $this->catName;
}
}
Already thanks for helping.
If you want more code from me just ask.
You are not binding parameters correctly.
Corrected code:
$query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName)");
$query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);
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
I have a MVC like store.
I wish to make a list of the most bought items (in this case prints, because it's a print store).
I'm finding it very hard specially because I'm very new to php / mysql and specially to this MVC structure... I hope this isn't a bad question.
I have a model.php like this :
<?php
class model {
private $conn;
function __construct() {
$server = "localhost";
$login = "root";
$pass = "";
$db = "printstore";
$conn = new mysqli($server, $login, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
$this->conn = $conn;
}
}
function __destruct() {
$this->conn->close();
}
function buildArr($result) {
$arr = array();
while ($row = $result->fetch_assoc()) {
array_push($arr, $row);
}
return $arr;
}
}
a controller.php:
<?php
include 'model.php';
class Controller {
private $model;
function __construct() {
$this->model = new model();
}
function home() {
include 'views/home.php';
}
}
a index.php:
<?php
session_start();
include 'controller.php';
define("BASE_URL", 'http://' . $_SERVER['SERVER_NAME'] . '/printstore2/index.php/');
define("MAIN_BASE_URL", 'http://' . $_SERVER['SERVER_NAME'] . '/printstore2/');
$controller = new controller();
include 'views/templates/header.php';
if (isset($_SERVER['PATH_INFO'])) {
$url = explode("/", $_SERVER['PATH_INFO']);
$function_name = $url[1];
if (isset($url[1]) && $url[1] !== "") {
if (isset($url[2])) {
$controller->$function_name($url[2]);
} else {
$controller->$function_name();
}
} else {
$controller->home();
}
} else {
include 'views/home.php';
}
include 'views/templates/footer.php';
And the view where I want to post the "Best Selling Prints":
<div>
<h2>Top Prints</h2>
<ol>
<li>1st print most bought</li>
<li>2nd</li>
<li>3rd</li>
</ul>
Now, my database has a table called "print_for_sale" which has the print_id and the sale_id, where I can see how many of each prints has been bought.
How can I do this? I'm so lost!
I'm sorry for the long post.
Use COUNT and GROUP BY
to get a list of all prints vs their sale count:
SELECT fk_print_id as printId, COUNT(print_for_sale_id) as saleCount
FROM print_for_sale
GROUP BY fk_print_id
ORDER BY saleCount DESC
that is, if i understood your table right.