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
Related
the warning message above is shown when the site is searched. It is a simple search feature which displays all the records, matching the search word with a field in the table. The code is as below.
if(isset($_POST['submit'])){
$clean_search_word = mysqli_real_escape_string($con,$_POST['search_word']);
$sql = "SELECT * FROM webdir_user where user_category like '%$clean_search_word%'";
$record = mysqli_query($con,$sql);
if(!$record){
die('Error in SQL:'.mysql_error());
}
else{
while($result = mysqli_fetch_array($record,$con)){
}
}
}
I have found answers to kind of same issues as mine, but in most of the cases the warning message was caused by something else so I couldn't find any help with figuring out what caused the problem in my case. Any help or advise as to how to resolve. Thank you.
Remove the $con from your mysqli_fetch_array and it should work. There is only 1 string allowed in this 'function'. The other one ($con) is optional and has to be an integer. Like MYSQLI_ASSOC
if(isset($_POST['submit'])){
$clean_search_word = mysqli_real_escape_string($con,$_POST['search_word']);
$sql = "SELECT * FROM webdir_user where user_category like '%$clean_search_word%'";
$record = mysqli_query($con,$sql);
if(!$record){
die('Error in SQL:'.mysql_error());
}
else{
while($result = mysqli_fetch_array($record)){
}
}
}
mysqli_fetch_array
takes one parameter (the $result)
another optional one which is INTEGER (int $resulttype = MYSQLI_BOTH )
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";
}
}
This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\xxx\dash.php on line 20
I am quite fairly new, and being a old-school coder, simply using mysql_result to grab such data, I am unaware of how to go about this. I have a class->function setup.
Line 20 of dash.php contains:
echo $user->GetVar('rank', 'Liam', $mysqli);
While, the function is:
function GetVar($var, $username, $mysqli)
{
$result = $mysqli->query("SELECT " . $var . " FROM users WHERE username = '" . $username . "' LIMIT 1");
return $result;
$result->close();
}
Now, to my understanding, I am meant to convert $result into a string, but I am not fully aware of how to do so. I've tried using a few methods, but to no avail. So I've come to the community to hopefully get a answer, I've also looked around but noticed that all other threads are asking for num_rows, while I just want to grab the string from the query select.
You have to fetch it first before echoing the results. Rough Example:
function GetVar($var, $username, $mysqli) {
// make the query
$query = $mysqli->query("SELECT ".$var." FROM users WHERE username = '".$username."' LIMIT 1");
$result = $query->fetch_assoc(); // fetch it first
return $result[$var];
}
Then use your function:
echo $user->GetVar('rank', 'Liam', $mysqli);
Important Note: Since you're starting out, kindly check about prepared statements. Don't directly append user input on your query.
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_object()) {
echo row['column_name'];
}
}
$result->close();
where you see 'column_name put the name of the column you want to get the string from.
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 );
I've got a page that contains a fair few database queries, each appended with or die(). I'm loading this page every 1 second for testing, and on random page loads (it could take two, it could take five, or ten) die() is switched and an error given.
I broke down the script, and managed to isolate the particular offending query, which is:
$fetch = mysql_fetch_assoc($result) or die("Error 3:" . mysql_error());
This particular line is contained within:
if($size > 0) {
$off_id = array();
while($row = mysql_fetch_assoc($result)) {
$off_id[] = $row['off_id'];
}
echo '<pre>';
var_dump($off_id);
echo '</pre>';
$rand = rand(0,$size);
$off_id = $off_id[$rand];
$query = "UPDATE rotation_data SET hit_counter = hit_counter + 1 WHERE off_id = '{$off_id}'";
$result = mysql_query($query) or die("Error 1:" . mysql_error());
$query = "SELECT * FROM offer_data WHERE off_id = '{$off_id}'";
$result = mysql_query($query) or die("Error 2:" . mysql_error());
$fetch = mysql_fetch_assoc($result) or die("Error 3:" . mysql_error());
$offer_url = $fetch['url']; $geo_target = $fetch['geo_target']; $blank = $fetch['blank'];
}
Things I noticed:
No mysql_error() is returned/printed. Only Error 3: is.
The $off_id array dumps correctly each and every time, so there's always an $off_id to be used in the previous $result query, and if there wasn't, that should trigger die() for the $result query instead.
I don't really understand why this would occur on random page loads, and not all the time, as this perhaps points to it not being a syntax issue, but a load issue?
However, even if it's a load issue, I don't understand why that particular query would fail and trigger a die() while the others are fine.
Any help in understanding why this might be, and suggestions of what I could do to fix this would be greatly appreciated!
I am guessing that your query here returns no results:
$query = "SELECT * FROM offer_data WHERE off_id = '{$off_id}'";
The following statement will not return FALSE, just an empty result set into $result.
// No results here this time...
$result = mysql_query($query) or die("Error 2:" . mysql_error());
And then you attempt to fetch a row from an empty result resource. This results in FALSE not because of error, but because there are no rows to fetch, and your short-circuit evaluation calls die().
We cannot see where you are setting $size, but it's possible that you are occasionally reading past the array bounds of $off_id by reaching a random value that is larger than that array.