Error : Array to string conversion in PHP - php

I'm getting this error while trying to execute my function.
The columns of my database are 100% correct and i tested every request and it worked!
Error :
[26-May-2018 05:21:49 UTC] PHP Notice: Array to string conversion in C:\wamp64\www\gcm\database.php on line 82
[26-May-2018 05:21:49 UTC] PHP Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\wamp64\www\gcm\database.php on line 88
My function:
function getHistoriqueNotification($user,$mdp){
$com = new DbConnect();
$message=array();
$sql="select UTLR_UID from adm_utilisateurs where UTLR_LOGIN='$user' and UTLR_MDP='$mdp'";
$result=mysqli_query($com->getDb(),$sql);
$getID = mysqli_fetch_assoc($result);
$userID = $getID['UTLR_UID'];
$sqli = "SELECT alr_alertes.ALRT_DES_LN1,alr_alertes.ALRT_PHOTO,alr_historiques.AHIS_DES_LN1,alr_historiques.AHIS_DATEHEURE from alr_alertes,alr_historiques WHERE alr_alertes.ALRT_UID=alr_historiques.ALRT_UID AND alr_historiques.UTLR_UID=$userID";
$resulti = mysqli_query($com->getDb(),$sqli);
while($row=mysqli_fetch_assoc($resulti)){
$message = array('photo' =>$row['ALRT_PHOTO'] , 'titre' => $row['ALRT_DES_LN1'] , 'dateHeure' =>$row['AHIS_DATEHEURE'] , 'detail' => $row['AHIS_DES_LN1']);
}
return $message;
}

When using mysqli you need to free up the results per each query. Since you made a query with the $sql and then a second query using the $sqli without freeing up the results in between the two queries it caused you the problem.
Please read on these mysqli functions:
http://php.net/manual/en/mysqli-result.free.php
Notice I closed your first connection and then made a second one. I think you can do this by keeping the same connection but calling mysqli_free_result() prior to your next query. I am not all that familiar with mysqli but I think that's right.
function getHistoriqueNotification($user, $mdp){
$com = new DbConnect();
$message=array();
$sql = "select UTLR_UID from adm_utilisateurs where UTLR_LOGIN='$user' and UTLR_MDP='$mdp'";
$result = mysqli_query($com->getDb(),$sql);
$getID = mysqli_fetch_assoc($result);
$userID = $getID['UTLR_UID'];
mysqli_close($com);
unset($com);
$com1 = new DbConnect(); //This is really just a test.
$sqli = "SELECT alr_alertes.ALRT_DES_LN1,alr_alertes.ALRT_PHOTO,alr_historiques.AHIS_DES_LN1,alr_historiques.AHIS_DATEHEURE from alr_alertes,alr_historiques WHERE alr_alertes.ALRT_UID=alr_historiques.ALRT_UID AND alr_historiques.UTLR_UID=$userID";
if ($resulti = mysqli_query($com1->getDb(), $sqli)){
while($row = mysqli_fetch_assoc($resulti)){
//Added the [] after message.
$message[] = array(
'photo' =>$row['ALRT_PHOTO'],
'titre' =>$row['ALRT_DES_LN1'],
'dateHeure' =>$row['AHIS_DATEHEURE'],
'detail' =>$row['AHIS_DES_LN1']
);
}
}else{
echo("Error description: " . mysqli_error($com1->getDb()));
}
print_r($message); //<---This will show you if you have a result.
return $message;
}

Related

Undefined Variable on mysqli_query

I have similar code that works with no errors but when I try and query my database I'm getting the several errors. Can anyone help ?
errors:
Notice: Undefined variable: link in C:\wamp64\www\twitter clone\functions.php on line 22
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\wamp64\www\twitter clone\functions.php on line 22
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\wamp64\www\twitter clone\functions.php on line 24
Code;
<?php
session_start();
$link = mysqli_connect("localhost", "root", "pass", "twitter");
if (mysqli_connect_errno()) {
print_r(mysqli_connect_error());
exit();
}
if (isset($_GET['function']) == "logout"){
session_unset();
}
function displayTweets($type) {
if ($type == 'public'){
$whereClause = "";
}
$query = "SELECT * FROM tweets ".$whereClause." ORDER BY 'datetime' DESC LIMIT 10";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) == 0) {
echo "No Tweets";
}
}
?>
The problem is that your $link variable is not in the function's local scope.
A way to fix this is by defining the variable in the function's local scope by adding the following line to the function:
global $link
Please have a look at this page to read more about the variable scope in PHP.
Edit:
An even better way would be to inject your connection by adding it as an argument to your function, which would have your code look something like this:
function displayTweets($type, $connection) {
if ($type == 'public'){
$whereClause = "";
}
$query = "SELECT * FROM tweets ".$whereClause." ORDER BY 'datetime' DESC LIMIT 10";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) == 0) {
echo "No Tweets";
}
}
After this, you would call your function using displayTweets('public',$link), with 'public' being the type, and $link being your defined connection
Also, in your current function, $whereClause could be undefined. I'm guessing your aware of this, just wanted to state it in case you get errors on that.
You have to use $link variable as global variable ($GLOBALS['link']) in displayTweets function or you have to pass $link as parameter.
$result = mysqli_query($GLOBALS['link'], $query);
or
displayTweets('public',$link);

Wordpress mysql_fetch_array() expects parameter 1 to be resource error

Very new to using mysql, however, I'm trying to fix a bug in an old piece of code in a wordpress plugin - here is the original code:
$sql = mysqli_query("SELECT count(`question_count`) as Qcount FROM `wp_posts` WHERE `question_count` = 1 and `question_date` = '".date("Y-m-d")."'") or die(mysql_error());
$no_of_questions = get_option( 'askme_setting_no_of_questions', 10 );
if($row = mysql_fetch_array($sql)) {
$qry = $row['Qcount'];
}
if($qry >= $no_of_questions) {
$value = "The question limit for today has been reached";
$button = "disabled";
} else {
$value = "Add your question to the cart";
$button = " ";
}
Which was giving the following error:
mysqli_query() expects at least 2 parameters, 1 given in
I have since changed the first line as follows to use Wordpress functions:
$sql = $wpdb->get_results( "SELECT count(`question_count`) as Qcount FROM `wp_posts` WHERE `question_count` = 1 and `question_date` = '".date("Y-m-d")."'" );
which now gives the following errors:
mysql_fetch_array() expects parameter 1 to be resource, array given in ...
Undefined variable: qry in ...
Is there something obvious that I am doing wrong here?
You should make mysqli connection first and then use queries and fetch queries further. You can follow the below link to use mysqli fetch queries.
https://www.w3schools.com/php/func_mysqli_fetch_array.asp
You're mixing things up.
mysql_ and mysqli_ are two completely different sets of functions in PHP. You can't send a query using the mysqli_ function, and manipulate the results with mysql_*.
Also, mysql_ functions were deprecated in later versions of PHP5, and removed altogether in PHP7.
Your best bet is to follow #tadman's advice and use WP's API for this.
Is the only line you changed the $sql = line?
From the wordpress codex:
global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );
should return you an array or object of results per the documentation.
so your code wouldn't need to do any of the fetch_assoc related methods. Wordpress is handling the actual DB connection and query parsing and just handing you back your results.
Possible Solution:
// formatting for readability.
$date = date("Y-m-d");
// Prepare query.
$sql = $wpdb->prepare(
"SELECT count(`question_count`) as Qcount
FROM `wp_posts`
WHERE `question_count` = 1
AND `question_date` = %s",
$date
);
// Execute query.
$results = $wpdb->get_results($sql);
// Get option for number of questions.
$no_of_questions = get_option( 'askme_setting_no_of_questions', 10);
// Set base values to avoid usage of else condition.
$value = "Add your question to the cart";
$button = " ";
// Check to ensure results returned.
if (!empty($results)) {
// Evaluate result of query.
if ($results[0]->Qcount >= $no_of_questions) {
// Update values only if necessary.
$value = "The question limit...";
$button = "disabled";
}
}

PHP count rows of specific entries in database

New to PHP and overwhelmed by all the different solutions to similar problems. I don't know if I have a coding problem, a multiple query problem, or both/more.
In one php file I am opening a connection, running a query, and then on success counting the number of times that entry appears in the database... or at least attempting to.
// $team1, $team2 and $page come in through _POST up here...
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// build long query at this point...
$result = mysqli_query($connection, $query);
//I was successful getting it into the database, now I want to count how many times each entry appears.
if ($result) {
$team1result = mysqli_query($connection,"SELECT * FROM {$page} WHERE 'vote' = {$team1}") ;
$team1row = mysqli_fetch_row($team1result);
$team1count = $team1row[0];
$team2result = mysqli_query($connection,"SELECT * FROM {$page} WHERE 'vote' = {$team2}") ;
$team2row = mysqli_fetch_row($team2result);
$team2count = $team2row[0];
echo $team1count . " and " . $team2count;
}
I'm able to insert into the database just fine but then my console.log lights up with...
Warning: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in...
Warning: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in ...
Thanks for all the help tonight.
SOLUTION (Thanks to wishchaser):
if ($result) {
$team1rows = mysqli_num_rows(mysqli_query($connection,"SELECT * FROM $page WHERE vote = '$team1'"));
$team2rows = mysqli_num_rows(mysqli_query($connection,"SELECT * FROM $page WHERE vote = '$team2'"));
echo $team1 . " : " . $team1rows . " | ". $team2 . " : ". $team2rows;
}
There were no resulting rows for queries $team1result and $team2result. That is why you are getting this error.
use a if statement to check this
if($team1result)
$team1row = mysqli_fetch_row($team1result);
if($team2result)
$team2row = mysqli_fetch_row($team1result);
You will not get the errors.
And for counting the number of rows that a query result, use the folowing
$rows=mysqli_num_rows(mysqli_query($query));
and a good practice of finding the mistake in your query statement would be to echo it.
in this case
echo "SELECT * FROM $page WHERE vote = '$team1'";
echo "SELECT * FROM $page WHERE vote = '$team2'";
check if the echoed query has no mistakes(like an undefined variable).
You can easily count this using num_rows no need to access its index and all, simply use this
echo $team1row = mysqli_num_rows($team1result);
Reference Link

How to separate arrays into variables

I've tried to look this up, but I'm not quite getting an answer that pertains directly to what I'm doing. I'm trying to retrieve values from a database that were previously submitted. I want to use these values to locate filepaths on the server and use the fillepath information to display the files. To do this, I need to separate the array that i have here. How would I separate this array?
$code = $_POST['codeInput'];
$code = htmlspecialchars($code);
$submitCodes = "SELECT story,video FROM `storycodes` WHERE `code` = $codeInput";
$files = mysql_fetch_array($submitCodes);
mysql_close($con);
print_r(array_values($files));
I appreciate any help guys. Ideally I would like to get a variable like $story or $storyPath and $video or $videoPath I need the video as a variable so I can play it with a video player.
EDIT:
I changed from mysql to mysqli and I'm getting all of these errors now that I can't seem to fix. I have the result set and it says I don't.
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in /home/content/98/10339998/html/scripts/stories.php on line 26
I think this warning should fix itself once the array gets sorted out:
Warning: extract() expects parameter 1 to be array, null given in /home/content/98/10339998/html/scripts/stories.php on line 28
Warning: mysqli_free_result() expects parameter 1 to be mysqli_result, boolean given in /home/content/98/10339998/html/scripts/stories.php on line 30
$con = mysqli_connect("storycodes.db.10339998.hostedresource.com",$username,$password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysqli_select_db($con, "storycodes");
$code = $_POST['codeInput'];
$code = htmlspecialchars($code);
$query = "SELECT story,video FROM `storycodes` WHERE `code` = $codeInput";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($result);
extract($row);
mysqli_free_result($result);
mysqli_close($con);
echo $story . $video;
use it like this
$files = mysql_fetch_array($submitCodes);
extract( $files );
// now you can use it like this
echo $story . $video; // as variables
$files = mysql_fetch_assoc( $submitCodes );
extract( $files );

mysql_query() returns returns true, but mysql_num_rows() and mysql_fetch_array() give "not a valid resource errors

Here is the code in question:
From index.php:
require_once('includes/DbConnector.php');
// Create an object (instance) of the DbConnector
$connector = new DbConnector();
// Execute the query to retrieve articles
$query1 = "SELECT id, title FROM articles ORDER BY id DESC LIMIT 0,5";
$result = $connector->query($query1);
echo "vardump1:";
var_dump($result);
echo "\n";
/*(!line 17!)*/ echo "Number of rows in the result of the query:".mysql_num_rows($result)."\n";
// Get an array containing the results.
// Loop for each item in that array
while ($row = $connector->fetchArray($result)){
echo '<p> <a href="viewArticle.php?id='.$row['id'].'">';
echo $row['title'];
echo '</a> </p>';
From dbconnector.php:
$settings = SystemComponent::getSettings();
// Get the main settings from the array we just loaded
$host = $settings['dbhost'];
$db = $settings['dbname'];
$user = $settings['dbusername'];
$pass = $settings['dbpassword'];
// Connect to the database
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
} //end constructor
//*** Function: query, Purpose: Execute a database query ***
function query($query) {
echo "Query Statement: ".$query."\n";
$this->theQuery = $query;
return mysql_query($query, $this->link) or die(mysql_error());
}
//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {
echo "<|";
var_dump($result);
echo "|> \n";
/*(!line 50!)*/$res= mysql_fetch_array($result) or die(mysql_error());
echo $res['id']."-".$res['title']."-".$res['imagelink']."-".$res['text'];
return $res;
}
Output:
Query Statement: SELECT id, title FROM articles ORDER BY id DESC LIMIT 0,5 vardump1:bool(true)
PHP Error Message
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /*path to*/index.php on line 17
Number of rows in the result of the query: <|bool(true) |>
PHP Error Message
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /*path to*/DbConnector.php on line 50
Your problem is in fallowing line:
return mysql_query($query, $this->link) or die(mysql_error())
it should have been written like this:
$result = mysql_query($query, $this->link);
if(!$result) die(mysql_error());
return $result;
It is common in dynamic languages that or returns first object which evaluates to true, but in PHP the result of X or Y is always true or false.
As you can learn from the manual, mysql_query return value type is not boolean but resource.
Something in your code converting it
Agree with above, you have an issue with your mysql_query. It should never return True. Either false or a resource.
Refactor : mysql_query($query, $this->link) or die(mysql_error())
echo mysqlerror() after your query and see what the error message is. You probably do not have a valid connection.

Categories