<?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);
}
Related
I am getting return values that do not exist in my current database. Even if i change my query the return array stays the same but missing values. How can this be what did i do wrong?
My MYSQL server version is 10.0.22 and this server gives me the correct result.
So the issue must be in PHP.
My code:
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Result:
array(1) {
[1]=> array(9) {
["UID"]=> string(1) "1"
["CreationTimestamp"]=> NULL
["UpdateTimestamp"]=> NULL
["ProcessState"]=> NULL
}
}
Solution:
I have found this code somewhere in my program. The program used the same name ass mine. This function turns the MYSQL result into a array. This happens between the result view and my script. This was done to make the result readable.
parent::processUpdatedAfter($date);
Function:
public function processUpdatedAfter($date)
{
$result = parent::processUpdatedAfter($date);
$array = Array();
if($result != false)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$array[$row["UID"]]["UID"] = $row["UID"];
$array[$row["UID"]]["CreationTimestamp"] = $row["CreationTimestamp"];
$array[$row["UID"]]["UpdateTimestamp"] = $row["UpdateTimestamp"];
$array[$row["UID"]]["ProcessState"] = $row["ProcessState"];
}
return $array;
}
return false;
}
I edited this and my script works fine now thanks for all the help.
Note that, var_dump($result); will only return the resource not data.
You need to mysql_fetch_* for getting records.
Example with MYSQLi Object Oriented:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['UID'];
}
}
else
{
echo "No record found";
}
$conn->close();
?>
Side Note: i suggest you to use mysqli_* or PDO because mysql_* is deprecated and closed in PHP 7.
You are var_dumping a database resource handle and not the data you queried
You must use some sort of fetching process to actually retrieve that data generated by your query.
$ts = '2016-09-20 08:56:43';
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > '$ts'";
$result = mysql_query($select_query, $link_identifier);
// did the query work or is there an error in it
if ( !$result ) {
// query failed, better look at the error message
echo mysql_error($link_identifier);
exit;
}
// test we have some results
echo 'Query Produced ' . mysql_num_rows($result) . '<br>';
// in a while loop if more than one row might be returned
while( $row = mysql_fetch_assoc($result) ) {
echo $row['UID'] . '<br>';
}
However I have to mention Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
$select_query = "SELECT `UID` FROM `process_state ` WHERE `UpdateTimestamp` > \"[given time]\" ORDER BY UID DESC ";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Try this hope it will works
In php I call a procedure in mysql. Now I want to check if a query result == true then set return variable in my php file in true or false if query failed. How can I do that?
This is my php code:
public function DeleteSingleAccount($accountId)
{
$Config = new Config();
$mysqli = $Config->OpenConnection();
mysqli_query($mysqli, "CALL DeleteSingleAccount($accountId)") or die("Query fail: ". mysqli_error());
}
This is my query in mysql for now:
DELETE
FROM table
WHERE accountId = par_AccountId
This code runs correct but I want to set an return parameter when query is true or false.
public function DeleteSingleAccount($accountId)
{
$Config = new Config();
$mysqli = $Config->OpenConnection();
return !! mysqli_query($mysqli, "CALL DeleteSingleAccount(" . intval($accountId) . ")");
}
I added intval() to avoid SQL injection (not needed if you're sure $accountId is always an integer, never null, empty string, user input, etc.)
Think your looking for something like this:
public function DeleteSingleAccount($accountId) {
$Config = new Config();
$mysqli = $Config->OpenConnection();
$result = mysqli_query($mysqli, "CALL DeleteSingleAccount($accountId)") or die("Query fail: ". mysqli_error());
//^Assignment of the query to a variable
if($result && mysqli_num_rows($result) > 0) {
//^Check if query is successfull ^ Check if query has 1 or more rows in it! (You can delete this check if you don't care about how many row's the result has)
echo "The query is successful and have 1 or more rows in it!";
} else {
echo "The query failed or have 0 rows in it!";
}
}
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?
I'm trying to call my function, but she's wrong.
I believe it is in connection variable.
Connection:
$conn = mysqli_connect('','','', '');
if(mysqli_connect_errno()) {
header("Location: error.php");
exit();
}
Function:
function t_car($id) {
global $conn;
$s_t_car = "SELECT *
FROM t_car
WHERE session='$id'";
$s_t_car_return = mysqli_query($conn, $s_t_car) or die("Erro SQL.".mysqli_error());
return $s_t_car_return;
}
Call Function:
$s_t_car_return = t_car($conn, $_SESSION['session_client']);
if(mysqli_num_rows($s_t_car_return )!=0) {
while($r_t_car = mysqli_fetch_array($s_t_car_return )) {
}
}
Error:
Catchable fatal error: Object of class mysqli could not be converted to string
At first you need to enter your settings from your MySQL server (mysql db).
$connection = mysqli_connect("HOSTNAME","USERNAME", "PASSWORD","DATABASE");
You can then use an if statement to check if the connection to the server has been made, if so, continue execution of following code, otherwise die();
If you want to fetch the data see below here:
$res = $connection->query("SELECT finger FROM hand WHERE index = 3");
while($row = $res->fetch_array())
{
print_r($row);
}
mysqli_query() returns a result. You have to fetch the result to do something with it.
$res = mysqli_query($conn, $s_t_car) or die("...");
$s_t_car_return = mysqli_fetch_row($res);
The following code in question always logs that the affected_rows was 0. I check my DB, the row updates fine everytime. Why is it 0?
public static function updateNextRunTime($nextRunTime)
{
$mysqli = new mysqli(GDB_HOST, GDB_USERNAME, GDB_PASSWORD, GDB_NAME);
if ($mysqli->connect_errno)
{
throw new Exception('DB Connection Failed. Error Code: ' . $mysqli->connect_errno);
}
$cmd = $mysqli->prepare("UPDATE balanceagent SET NextRunTime = ? WHERE Id = 1");
if (!$cmd)
{
throw new Exception($mysqli->error);
}
$cmd->bind_param('s', $nextRunTime);
$cmd->execute();
$rows = $mysqli->affected_rows;
$cmd->close();
$mysqli->close();
if ($rows != 1)
{
logToFile("Balance Agent Error - Failed to update the next run time! - Affected rows: " . $rows);
}
}
For prepared statements you should be using the mysqli_stmt::affected_rows form :
$cmd->bind_param('s', $nextRunTime);
$cmd->execute();
$rows = $cmd->affected_rows;
Your should check
$cmd->affected_rows;
instead of
$mysqli->affected_rows;