Call to undefined function query() when it is defined - php

I have searched through similar questions and can't find the answer, though I am a beginner so may have missed it.
I am trying to call the review_create() function I have included the reviews.php which contains this function. However, I am getting the error
Fatal error: Call to undefined function query() in C:\xampp\htdocs\cafe\review.php
The PHP for user_pages.php:
<?php
require_once 'review.php';
require_once 'cafe.php';
require_once 'logged_in.php';
$RATING_MAP = array('5' => 'Excellent', '4' => 'Good', '3' => 'Ok', '2' => 'Bad', '1' => 'Awful', '0' => '---');
$error = array();//holds multiple errors
$id = $rating = $review = $action = '';
$self = $_SERVER['PHP_SELF'];
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
}
if ($action == 'delete') {
if (isset($_REQUEST['id'])) {
review_delete($_REQUEST['id'], $error);
} else {
$error[count($error)] = "Cannot delete the review, missing ID!";
}
}
elseif ($action == 'create') {
if ((isset($_REQUEST['rating']))
&& (isset($_REQUEST['review'])
&& (isset($_REQUEST['review_cafe'])))) {
$rating = $_REQUEST['rating'];
$review = $_REQUEST['review'];
$review_cafe = $_REQUEST['review_cafe'];
if ($rating == '---' or $review == '' or $review_cafe == '') {
$error[count($error)] = "You must provide a cafe, rating and review!";
} else {
review_create($review_cafe, $rating, $review, $error);
}
}
else {
$error[count($error)] = "Unable to create review, missing parameters!";
}
}
?>
The PHP for reviews.php:
<?php
require_once "sql.php";
function review_create($review_cafe, $rating, $review, &$error) {
$query = "INSERT INTO Reviews (cafe, rating, review) VALUES (". "'$review_cafe', $rating, '$review');";
$success = query($query, $error);
return $success;
}
?>
Here is sql.php where $query is defined:
<?php //sql.php
require_once "sql_constants.php";
class Sql {
private static $connection = false;
private static $error; // holds the last error.
static function getConnection() {
if (!Sql::$connection) {
Sql::setConnection(mysqli_connect(SQLHOST, SQLUSER, SQLPASSWORD, HOSTDB));
if (!Sql::$connection) {
Sql::setConnection(false);
Sql::setError("Could not connect...");
}
}
return Sql::$connection;
}
private static function setConnection($iConnection) {
Sql::$connection = $iConnection;
}
private static function setError($iError) {
Sql::$error = $iError;
}
static function getError() {
return Sql::$error;
}
static function query($query) {
$result = false;
Sql::setError(false); // reset the error
if ($link = Sql::getConnection()) {
$result = mysqli_query($link, $query);
if (!$result)
Sql::setError(mysqli_error($link));
}
return $result;
}
static function getInsertID() {
// Returns the last id automatically inserted into the
// database.
return mysqli_insert_id(Sql::getConnection());
}
}
?>
Cheers
James

Avoid using mysql, use mysqli_ instead and update your code to use mysqli_query in place of query (that is the error!!)
simply do :
return (mysqli_query( $conn, $query )); //$conn is connection object
OR, if you are doubtfull of result, use mysqli_error()
$success = mysqli_query($con, $query);
if ( $success === false)
{
printf("Error is : ", mysqli_error($con));
}
else
{
return ($success);
}

error here- $success = query($query, $error);
It should be - $success = mysql_query($query, $error);
unless You do have a method query() which executes the query

I prefer to use PDO or MYSQLI instead of that, which is easy to inject. (http://en.wikipedia.org/wiki/SQL_injection) see http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

Related

PDO UPDATE array using php mysql

Hello I'm trying to make a code to UPDATE or EDIT the survey answers and comments per answer but when I execute the function submiting the form, it did not save any value into the database. What can I do to fix it?
I'm new in PDO.
Thanks in advance.
Database Structure
"Questions" (idquestion, question)
"Surveys" (idsurvey, idquestion, answers, comments_per_question, survey_number)
Update function
public function ModifySurveyMulti($answer = array())
{
if(!empty($answer)) {
foreach($answer as $questi => $value ) {
$this->MyDB->Write("UPDATE survey SET(
`idquestion` = '".$questi."',
`answers` = '".$value[0]."',
`comments_per_answer`= '".$_POST["comment"][$questi]."')");
}
}
}
modify_surveyform.php
<th><?php echo $row["questions"];?></th>
<td>
<input type = "text"
name = "answer[<?php echo $row['idquestion'];?>][]"
value = "<?php echo $row["answers"];?>">
</input>
</td>
<td>
<Textarea type = "text"
name = "comment[<?php echo $row['idquestion'];?>]"
cols = "50" rows = "3"/> <?php echo $row["comment"];?
</textarea>
</td>
</tr><?php } ?>
Mydbconnect.php
<?php
// I'm adding my PDO database because yours is deprecated
class DBConnect
{
public $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;
dbname=$db",$user,
$pass, array(
PDO::ATTR_ERRMODE
=> PDO::ERRMODE_WARNING
)
);
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
while($array = $query->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $array;
}
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}?>
Few things you need to do:
First of all ditch this code, it is useless and expose you to sql
injection
Use PDO directly with prepared statement
The query you need is :
UPDATE survey SET(`answers`= ?,`comments_per_answer`= ?) WHERE idquestion = ?
You will need to adjust your class to only create the connection
class DBConnect
{
public $con;
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO(
"mysql:host=$host;dbname=$db",
$user,$pass,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING)
);
}
catch (Exception $e) {
die($e);
}
}
public function get_connection(){
return $this->con;
}
}
So that you can create it like this:
$db = new DBConnect(/*pass arguments here*/);
$this->MyDB = $db->get_connection();
Modify and use it in your function:
public function ModifySurveyMulti($answer = array(), $comments)
{
$sql = 'UPDATE survey SET(`answers`= ?,`comments_per_answer`= ?)
WHERE idquestion = ?';
$stmt->prepare($sql);
foreach($answer as $questi => $value ) {
$stmt->execute(array($value, $comments[$questi],$questi));
$count = $stmt->rowCount();
echo $count > 0 ? $questi.' updated' : $questi.' did not update';
}
}
Call the function :
if(isset($_POST['answer'], $_POST['comments'])){
$answers = $_POST['answer'];
$comments = $_POST['comments'];
ModifySurveyMulti($answers, $comments);
}

PDO "Invalid parameter number: parameter was not defined" yet it is

Basically what I'm doing is a users class, which executes a MySQL query in the constructor to retrieve all the users data and store it, like so:
public function __construct($data, $type = 'id')
{
$this->details = Beam::$db->row("SELECT * FROM users WHERE $type = :param", ['param' => $data]);
if(!empty($this->details)) $this->exists = true;
}
This is row() method:
public function row($query, $params = null, $fetchmode = PDO::FETCH_ASSOC)
{
$this->init($query, $params);
return $this->statementQuery->fetch($fetchmode);
}
And init(), where the parameters are bound and the query is executed:
public function init($query, $parameters = '')
{
try {
$this->statementQuery = $this->pdo->prepare($query);
if(!empty($parameters))
{
foreach($parameters as $key => $value)
{
$this->bind($key, $value);
}
}
if(!empty($this->parameters))
{
foreach($this->parameters as $key => &$value)
{
$this->statementQuery->bindParam($key, $value);
}
}
$this->success = $this->statementQuery->execute();
}
catch(PDOException $e)
{
throw new SystemException($e->getMessage() . ' in query: ' . $query, (int) $e->getCode());
}
$this->parameters = array();
}
It should work, I've tested everything multiple times, and debugged using dies() everywhere, but it seems as if I instantiate the class more than one time, the error occurs. It's called multiple times in all my code. Is there something I'm missing?
The error:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in query: SELECT * FROM users WHERE id = :param
I've also tried debugging printing all the parameters set in PDO by ::debugDumpParams(), and all the parameters are okay, I even var_dump the $this->statementQuery->fetch($fetchmode) from the row() method and it returns everything as it should be...
PS: I bind the array ['param' => $data] afterwards, using this method:
public function bind($param, $value)
{
$this->parameters[':' . $param] = $value;
}
Some examples of where I call the class from:
Login method. Called when the user does login. It fails.
public static function login($user, $password)
{
$user = new User($user, Beam::$con->auth['type']);
if($user->exists == true)
{
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$user_id = $user->details["id"];
$username = $user->details["username"];
$user_mail = $user->details["mail"];
$user_password = $user->details["password"];
if(self::verify($password, $user_password))
{
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['user_mail'] = $user_mail;
$_SESSION['user_checksum'] = hash('sha512', $user_password . $user_ip . $user_browser);
Beam::$db->bind("l", time());
Beam::$db->bind("u", $user_id);
Beam::$db->query("UPDATE user_info SET login_timestamp = :l WHERE user_id = :u");
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
This one checks if the user is logged in. It's called almost in every file for authenticated users only.
public static function status()
{
if(isset($_SESSION["user_id"], $_SESSION["username"], $_SESSION["user_checksum"]))
{
$user = new User($_SESSION["user_id"], "id");
if($user->exists)
{
$user_id = $_SESSION['user_id'];
$user_checksum = $_SESSION['user_checksum'];
$username = $_SESSION['username'];
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$user_password = $user->details["password"];
switch($user_checksum)
{
default:
$checksum_verify = hash('sha512', $user_password . $user_ip . $user_browser);
break;
case "facebook":
$checksum_verify = "facebook";
break;
}
if($checksum_verify == $user_checksum)
{
return true;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
You need to use the same name for the parameter that you used in the query. In this case you used ":param" so that's what you need to use when you pass in the array of parameters.
change
['param' => $data]
to
[':param' => $data]
and it should work.

PHP: Fatal error: Call to a member function query() on a non-object [duplicate]

This question already has an answer here:
php error Call to a member function query() on a non-object [closed]
(1 answer)
Closed 9 years ago.
i have this class for connect to MySql database and create/insert user but when work with this i see error.
My Auth Class is:
class AuthDB {
private $db;
public function __construct() {
$db = new Dbaccess();
if (!$db->connect ( DB_SERVER, DB_USER, DB_PASS, DB_NAME ) ) {
if (mysql_error() == '')
$database_incorrect = 'Database name is incorrect or doesn\'t exist';
else
$database_incorrect = 'ERROR: ';
echo $database_incorrect . mysql_error ();
}
}
public function createUser($email, $password, $salt, $verification) {
$ver = 0;
$act = 1;
$adm = 0;
$MYSQLDB = "INSERT INTO tbUsers (email, password, user_salt, is_verified, is_active, is_admin, verification_code) "
. "VALUES ('1', '1', '1', '1', '1', '1', '1')"; //test value
$r2 = $db->query ($MYSQLDB) or error ('Critical Error', mysql_error () ); // <<<LINE 30 ERROR HERE
if ($r2 > 0) {
return true;
}
return false;
}
}
My Dbaccess class Is:
class Dbaccess
{
var $q_array = array();
var $db_id;
var $query;
var $counter = 0;
var $timecounter = 0;
var $query_res;
function connect ($host, $login, $password, $db)
{
$this->host = $host;
$this->login = $login;
$this->password = $password;
$this->db = $db;
$this->db_id = #mysql_connect($this->host, $this->login, $this->password);
if ($this->db_id)
{
$db_select = #mysql_select_db($this->db);
$this->query("SET NAMES 'UTF8'");
if (!$db_select)
{
#mysql_close($this->db_id);
$this->db_id = $db_select;
}
else
return $this->db_id;
}
else
return false;
}
function close()
{
if($this->db_id)
{
if($this->query)
{
#mysql_free_result($this->query);
}
$result = #mysql_close($this->db_id);
return $result;
}
else {
return false;
}}
function query ($query)
//
// $db->query("QUERY");
{
unset($this->query_res);
if($query != "")
{
$sql_start = explode(' ', microtime());
$this->query_res = #mysql_query($query, $this->db_id);
$sql_stop = explode(' ', microtime());
$sql_time = $sql_stop[0] - $sql_start[0];
$sql_time+= $sql_stop[1] - $sql_start[1];
$this->timecounter+= round($sql_time, 5);
$this->counter++;
}
if($this->query_res)
{
unset($this->q_array[$this->query_res]);
return $this->query_res;
}
else
{
return false;
}
}
}
Now i see this error when send data :
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\test\classes\Auth.php on line 30
How to Fix This Error? Where is my mistake?
You want this in your __construct:
public function __construct() {
$this->db = new Dbaccess();
And when you query, you want:
$this->db->query($MYSQLDB);
When you just use the variable $db, it only exists within the scope of that method. But when you use class properties it exists within the scope of the entire class.

Database class design

I'm creating a web app with various classes for things like the user, Smarty template control, etc.
I already have a database class which is all well and good, but I'm concerned about the performance of it.
Currently, in another class, I'm doing $this->db = new DB() to create a local database instance, however the database class's __construct() function creates a new connection to the MySQL server every time I make a new DB() instance, which is obviously less than sensible. This means that each instance of all my different classes that uses the database class makes a connection to the server. I don't have a vast amount of classes, but I only want one per page load.
This is a stripped down sample of what I have at the moment:
// Database class used by multiple other classes
class DB {
private $dbh;
function __construct() {
$this->dbh = // PDO connection here
}
public function query($str) {
// Do a query
}
}
// Example class User
class User {
private $db; // Stores local instance of DB class.
function __construct() {
$this->db = new DB(); // Makes a new connection in DB::__construct()
}
public function login() {
$this->db->query('SELECT * FROM users');
}
}
I'm looking for the "best" or most common practice of doing this. I don't want to make 10-ish separate connections for each page load.
I want to know what the best way of using and managing a DB class in my application. My four thoughts are these:
Would using a persistent connection to the MySQL server solve this multiple connection issue for me?
Should I use a static factory class and return a DB instance instead of using new DB()?
Is the proper solution to use an entirely static class and just do DB::query() (for example) every time I reference it?
I often use multiple classes in another (so we might have class Folders which requires classes User, DB and Smarty). Is it general practice to extend each class somehow?
If you make the variable holding the connection static, then you can check if you already established a connection. Static variables are the same across all instances of the class, so you can create 100 instances that all use the same connection. You just need to reference it statically: self::$dbh instead of $this->dbh.
class DB {
private static $dbh = null;
function __construct() {
if ( is_null(self::$dbh) ) {
self::$dbh = // PDO connection here
}
}
}
I would suggest you to check the $this -> db at first and then only create it.
function __construct() {
if(!isset($this -> db) || !is_a("DB", $this -> db)) {
$this->db = new DB(); // Makes a new connection in DB::__construct()
}
}
You need to inject db connection to your class instead of creating a new connection.
// In a bootstrap file
$db = new DB();
// User.php
class User {
private $db;
function __construct($db=null) {
if (!is_null($db)) {
$this->setConnection($db);
}
}
function setConnection($db) {
$this->db = $db;
}
public function login() {
$this->db->query('SELECT * FROM users');
}
}
BTW, Zend_Registry is a good solution if you prefer it http://framework.zend.com/manual/en/zend.registry.using.html
<?php
class DBLayer {
public $prefix;
public $link_id;
public $query_result;
public $saved_queries = array();
public $num_queries = 0;
public function DBLayer() {
$db_prefix = '';
$this->prefix = $db_prefix;
if (isset($this->link_id)) {
return $this->link_id;
}
$this->link_id = #mysql_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, true);
if ($this->link_id) {
if (#mysql_select_db(DATABASE_NAME, $this->link_id)) {
return $this->link_id;
} else {
$this->wplog("Unable to select database. Host:". DATABASE_HOST. "Database:" . DATABASE_NAME . " Error: " . mysql_error(), 'ERROR', __FILE__, __LINE__);
}
} else {
$this->wplog("Unable to connect to MySQL server. Host: " . DATABASE_HOST . " Error: " . mysql_error(), 'ERROR', __FILE__, __LINE__);
}
}
public function query($sql, $unbuffered = false) {
if(LOG){echo "<hr>$sql";}
$this->query_result = #mysql_query($sql, $this->link_id);
if ($this->query_result) {
return $this->query_result;
} else {
$msg= $sql . "<br /> Error: (" . mysql_errno() . ") " . mysql_error();
$this->wplog($msg);
}
}
public function result($query_id = 0, $row = 0) {
return ($query_id) ? #mysql_result($query_id, $row) : false;
}
public function fetch_assoc($query_id = 0) {
return ($query_id) ? #mysql_fetch_assoc($query_id) : false;
}
public function fetch_row($query_id = 0) {
return ($query_id) ? #mysql_fetch_row($query_id) : false;
}
public function num_rows($query_id = 0) {
return ($query_id) ? #mysql_num_rows($query_id) : false;
}
public function affected_rows() {
return ($this->link_id) ? #mysql_affected_rows($this->link_id) : false;
}
public function insert_id() {
return ($this->link_id) ? #mysql_insert_id($this->link_id) : false;
}
public function get_num_queries() {
return $this->num_queries;
}
public function get_saved_queries() {
return $this->saved_queries;
}
public function free_result($query_id = false) {
return ($query_id) ? #mysql_free_result($query_id) : false;
}
public function escape($str) {
if (function_exists('mysql_real_escape_string'))
return mysql_real_escape_string($str, $this->link_id);
else
return mysql_escape_string($str);
}
public function get_select($q, $onlyone=false) {
$results = array();
$r = $this->query($q);
if ($onlyone) {
return $this->fetch_assoc($r);
}
while ($l = $this->fetch_assoc($r)) {
$results[] = $l;
}
return $results;
}
public function get_error() {
return mysql_error();
}
public function close() {
if ($this->link_id) {
if ($this->query_result)
#mysql_free_result($this->query_result);
return #mysql_close($this->link_id);
}
else
return false;
}
public function auto_execute($table, $data, $type, $criteria='') {
$result = $this->get_select("desc " . $table);
if ($type == "INSERT")
$start = "insert into " . $table . " set ";
elseif ($type == "UPDATE")
$start = "update " . $table . " set ";
$sql = $start;
foreach ($result as $rst) {
foreach ($data as $key => $value) {
if ($key == $rst['Field'] and $key !== 0) {
if ((#ereg('date', $rst['Type'])) && $value == '') {
$sql = $sql . "`".$key."`" . "=NULL, ";
} elseif ((!#ereg('int', $rst['Type']))) {
$sql = $sql . "`".$key."`" . "='" . $value . "', ";
} else {
if (trim($value) != "") {
$sql = $sql . "`".$key."`" . "=" . $value . ", ";
}
}
}
}
}
if ($sql == $start)
return 0;
else {
$sql = substr($sql, 0, strlen($sql) - 2);
if ($type == "UPDATE" and !empty($criteria))
$sql = $sql . " where " . $criteria;
}
//echo $sql;exit;
if ($this->query($sql)) {
$return = $this->insert_id();
} else {
$return = 0;
}
return $return;
}
private function wplog($message) {
if(LOG==true){
$lineBreak = "\n"; // this function will NOT work on a windows server without further modification
$contents = date('Y-m-d H:i:s') . ' ' . $message. $lineBreak;
$myFile = SERVER_PATH.'/log.txt';
$fh = fopen($myFile, 'a') ;
fwrite($fh, $contents);
fclose($fh);
//SetFileContents(SERVER_PATH.'/log.txt',$contents,'a');
}
}
}

Trouble with php (call to a member function on a non-object)

I am getting this php error and I can't seem to fix it.
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\mlrst\database.php on line 26
here is the line that is calling function prepare.
$this->statement->prepare($strQuery);
and here is it being declared.
protected $statement;
any ideas?
Edit: Here is my full code (don't mind the testing dummies)
<?php
$d = new database(); // test
class database {
protected $db_connect;
protected $statement;
function database() {
$db_connect = new MySQLi("localhost", "root" ,"", "test") or die("Could not connect to the server.");
$statement = $db_connect->stmt_init();
$this->preparedQuery("INSERT INTO feedback (name, feedback) VALUES ('?', '?')");
$this->close();
echo "Done!";
}
protected function cleanString($strLine) {
$strCleansedLine = preg_replace("/[^a-zA-Z0-9\s]/", "", $strLine);
return $strCleansedLine;
}
public function preparedQuery($strQuery, $parameters = NULL) {
try {
$this->statement->prepare($strQuery);
$statement->bind_param("ss", $name, $feedback);
for ($i = 0; $i < count($parameters); $i++) {
}
$name = $this->cleanString("this is my name");
$feedback = $this->cleanString("this is some feedback");
$query = $statement->execute();
} catch(Exception $e) {
echo $e->getMessage();
}
}
protected function close() {
try {
if ($this->statement != NULL)
$this->statement->close();
if ($this->db_connect != NULL)
$this->db_connect->close();
} catch (Exception $e) {
$e->getMessage();
}
}
}
?>
You assigned the local variable $statement. You need to set the instance's property using $this->statement.
In other words, change this:
$statement = $db_connect->stmt_init();
To this:
$this->statement = $db_connect->stmt_init();
And this:
$statement->bind_param("ss", $name, $feedback);
To this:
$this->statement->bind_param("ss", $name, $feedback);
...and this:
$query = $statement->execute();
To this:
$query = $this->statement->execute();

Categories