PHP MySQLi calling 3 different procedures error - php

I want to call 3 different procedures in one connection
but i still get error
Fatal error: Call to a member function fetch_object() on a non-object
but calling one at a time works for every call.
Code bellow::
$db = new mysqli($hostname, $username, $password, $database);
...
$sql1 = "CALL `something`.`proc_something1`(4,10);";
$sql2 = "CALL `something`.`proc_something2`(4,10);";
$sql3 = "CALL `something`.`proc_something3`(4,10);";
$results1 = $db->query($sql1);
while($row1 = $results1->fetch_object()){
print_r($row1);
echo '<br/>';
}
$results2 = $db->query($sql2);
while($row2 = $results2->fetch_object()){
print_r($row2);
echo '<br/>';
}
$results3 = $db->query($sql3);
while($row3 = $results3->fetch_object()){
print_r($row3);
echo '<br/>';
}
is there an easy way to correct code above?

Related

Fatal error: Call to undefined method MDB2_Error::execute() on line 30 (SQLyog)

I currently working on dashboard using PHP. I need to fetch data from database inside SQLyog, and transfer it into a graph. The problem is I keep getting this error; Fatal error: Call to undefined method MDB2_Error::execute() on line 30 in the class coding. The error is on $res = $query->execute($data); Can someone help me with my coding?
Here is the code for class.
<?php
class fetch_ranking extends MDB2{
var $con;
var $tbl_user;
var $tbl_isi_scopus_webo;
function fetch_ranking ($dsn) {
$this->con =& MDB2::singleton($dsn, $options=null);
//echo $this->con->getMessage();
if (PEAR::isError($this->con)) {
die($this->con->getMessage());
}
$this->tbl_user = 'user';
$this->tbl_isi_scopus_webo = 'ISI_SCOPUS_WEBO';
}
function fetch_webojuly16(){
$types = array();
$sql = "select university, criteria_rank as presence
from isi_scopus_webo
where month='july'
and year='2016'
group by university" ;
$query = $this->con->prepare($sql,$types,MDB2_PREPARE_RESULT);
$data = array();
$res = $query->execute($data);
if (PEAR::isError($res)) {
die($res->getMessage());
}
$this->con->setFetchMode(MDB2_FETCHMODE_ASSOC);
$valrec = $res->fetchAll();
return $valrec;
}
}?>
And this is for the graph.
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/config/siteconf.php');
require_once($basehome.'/config/default.php');
require_once($basedir.'/mod/ppsg/dsn.php');
require_once($basehome.'/mod/ppsg/class/fetch_data_from_db_isi_scopus_webo.php');
$current_year = date('Y', strtotime(date('Y')));
//$fhObj = new fetch_ranking($ranking);
$hostname="192.168.111.55";
$username="devopt";
$password="G0devopt$";
$dbname="ranking";
//Connect to the database
$connection = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
mysql_select_db($dbname, $connection)
or die("Could not select examples");
$xdata=array();
$ydata=array();
$xdata['name'] = 'PRESENCE';
$ydata['name'] = 'UNIVERSITY';
$ydata['color'] = '#ABEBC6';
//Call to a member function fetch_webojuly16() on a non-object
$webojuly16 = $fhObj->fetch_webojuly16();
foreach($webojuly16 as $wj16){
$xdata['data'][] = $wj16['presence'];
$ydata['data'][] = $wj16['university'];
}
$json_arr = array($xdata,$ydata);
print json_encode($json_arr, JSON_NUMERIC_CHECK);
?>
This is the coding for graph
The $this->con->prepare($sql,$types,MDB2_PREPARE_RESULT); call might return a MDB2_Error object in case the prepare() statement fails, as documented on http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare. You have to check with PEAR::isError if that is the case or not. In your case it is, so you cannot call $res = $query->execute($data); on a MDB2_Error object, and that's exactly what the error message is telling you.
Add the if statement to check for errors on the $query variable and check the error messages you get.

Fatal error: Call to a member function fetch_assoc() on a non-object occurs when i try to run my php

I have made a database with two tables name 'user'&'volley'. This php code helps me to connect those tables and retrieve the data.
i get this error
Fatal error: Call to a member function fetch_assoc() on a non-object
in /home/u115908902/public_html/Wishes.php on line 11
while i try to run my php code .
<?php
$mysqli = NEW MySQLi("mysql.hostinger.in","willi","123","pract");
global $mysqli;
$resultSet = $mysqli->query("SELECT user.name AS userName,
volley.wishes AS userWishes
FROM user,volley
WHERE user.name = 'mick' AND volley.id=user.id");
$resultSet = array();
while($rows = $resultSet->fetch_assoc()){
array_push($resultSet,
array(
$users = $rows['userName'],
$volleys = $rows['userWishes']));
echo json_encode(array("resultSet"=>$resultSet));
mysqli_close($con);
}
?>
You are destroying your result set with the line $resultSet = array();
Also you are making the unload of the resultset overly complex it does not need to be
<?php
$mysqli = NEW MySQLi("mysql.hostinger.in","willi","123","pract");
// remove this line its nonsence
//global $mysqli;
$resultSet = $mysqli->query("SELECT user.name AS userName,
volley.wishes AS userWishes
FROM user,volley
WHERE user.name = 'mick' AND volley.id=user.id");
// remove this line it destroys your resultset
//$resultSet = array();
$results = array();
while($row = $resultSet->fetch_assoc()){
$results[] = $row;
}
// this does not belong in the loop
mysqli_close($mysqli);
// nor does this
echo json_encode($results);
?>

Select the most recent 5 rows based on date

I haven't touched PHP in a while and trying to select the 5 most recent entries in my database and print them to screen.
I see mysql command isn't recommended anymore and to use PDO->mysql instead.
My query is something like this:
SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5;
I'm assuming I would have to put the values into an array and create a loop and output the results.
<?php
$db = new PDO('mysql:dbhost='.$dbhost.';dbname='.$dbname, $user, $pass);
while () {
print($title[$i], $date[$i], $author[$i]);
$i++
}
$db = null;
?>
I'm stuck filling in the gaps with the above code.
Update: The $db = new PDO.... line is reporting an error message:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] Can't connect to local MySQL server through socket... in /var/...
PDO is confirmed to be installed and enabled. My other web apps on the server can connect to the same remote mysql server fine.
<?php
$host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-password';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
<?php
$sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5";
$query = $conn->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
?>
<?php do {
// print your results here ex: next line
echo 'Title: '.$row['title'].' Date: '.$row['date'].' Author: '.$row['author'].'<br>';
} while ($row = $query->fetch(PDO::FETCH_ASSOC)); ?>
Don't forget to close and release resources
<?php $query->closeCursor(); ?>
EDIT
I recommend not echoing error messages once you have confirmed your code functions as expected; however if you want to simply use plain text you can do this...
You can add this to your connection block...
if ($conn->connect_error) {
die("Database Connection Failed");
exit;
}
You can also change your query block...
try {
$sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5";
$query = $conn->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die("Could not get the data you requested");
exit;
}
Again, it is recommended that errors not be echoed. Use error checking only for debugging.
<?php
$db = PDO('mysql:dbhost=$dbhost;dbname=$dbname', $user, $pass);
$sth = $db->prepare("SELECT id,title,date,author FROM table ORDER BY date LIMIT 5");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
?>
in a loop:
while($row = $sth->fetch()) {
echo $row['column'];
}
From the documentation: http://php.net/manual/en/pdostatement.fetch.php

PHP fetch_object() on a non-object

<?php
$id = $_POST["id"];
$id2 = $_POST["id2"];
$db = new mysqli('localhost', '***', '***', '***');
if (mysqli_connect_errno() == 0) {
$sql = "SELECT * FROM chat_message WHERE id > " . $id . " AND id <= " . $id2 . " ORDER BY id";
$result = $db->query($sql);
while ($msg = $result->fetch_object()) {
?>
<div>...</div>
<?php
}
}
$db->close();
?>
I am getting this error:
Call to a member function fetch_object() on a non-object in /var/www/template/loadchat.php on line 11
Line 11:
while ($msg = $result->fetch_object())
Any help? Because I work on this thing since yesterday and I can't find the mistake.
1) Verify if your db table is named like chat_message (maybe it is chat_messages?)
2) Verify if your chat_message.id field exists
3) Verify if your php variables $id and $id2 are integer/float numbers!
$result = $db->query($sql); is returning false. This means that the query failed for some reason.
Quoting the PHP manual for mysqli::query:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
To check for an error you can do:
if (!$db->query($sql)) {
trigger_error('Database error: '. $db->error);
}

I'm a little confused, PHP says $results is a non-object of the mysqli class

I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:
Fatal error: Call to a member function fetch_row() on a non-object in...on line 23.
The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?
class mySQLHelper{
public function checkPass($user, $pass){
global $db;
$db = new mysqli();
$db->connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()){
echo 'Can not connect to database';
echo mysqli_connect_errno(). mysqli_connect_error();
exit;
return false;
}
$query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;
echo $query;
$results = $db->query($query);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
$results->close();
$url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
if(!$results){
// mysqli_close($db);
// header("Location:.$url.login.php&msg=1");
}
else{
// mysqli_close($db);
// header("Location:.$url.featured.php");
}
}
}
Your query is failing on this line:
$results = $db->query($query);
Because of this, $results is false - not a result object as you expect.
To fix the issue, you need to add quotes around your variables (or use prepared statements):
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:
$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();
You script is lacking error checking, and therefore the error in the query is not handled.
$query = "SELECT user, password FROM Users
WHERE user = '$user' AND password = '$pass' " ;
// ^ quotes needed
echo $query;
$results = $db->query($query);
// handle a error in the query
if(!$results)
die($db->error);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
If you user & password field text or varchar, then you need to use single quote around them
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
You have to check, if query runs properly:
if ($result = $mysqli->query($query))
{
}
Use: var_dump($results) to check what it contains
Why are you checking if($results) after trying to manipulate it?
This...
$results->close();
//...
if(!$results){
//...
}
Should be...
if(!$results){
//...
}
$results->close();

Categories