Using PHP/MySQL to Calculate Percentages - php

I'm trying to calculate the number of students who've completed an their homework for an online gradebook, and I can't figure the code out...
// SELECT THE TOTAL
$gettotal = "SELECT enroll FROM student_course WHERE classID = $classID";
$showtotal = #mysqli_query ($dbc, $gettotal); // Run the query.
//THIS IS LINE 108
$numtotal = mysql_num_rows($showtotal);
echo '$numtotal';
// SELECT THOSE PASSED
$getpassed = "SELECT entry FROM grades WHERE classID = $classID AND test_result >= 80";
$showpassed = #mysqli_query ($dbc, $getpassed); // Run the query.
$numpassed = mysql_num_rows($showpassed);
//THIS IS LINE 117
echo '$numpassed';
// PERFORM THE PERCENTAGE FUNCTION
function percent($numpassed, $numtotal) {
$count1 = $numpassed / $numtotal;
$count2 = $count1 * 100;
$count = number_format($count2, 0);
echo $count;
}
//THIS IS LINE 124
percent($numpassed, $numtotal);
I get the following error:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource on line 108
$numtotal
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource on line 117
$numpassed
Warning: Division by zero in on line 124
0

Okay - while I thank everyone for their concern removing the # ... no one noticed that the problem was using mysqli_query and then mysql_num_rows. It needed to be changed to mysqli_num_rows.
Thanks though :)

Chances are the query has failed.
Also mysql_query will return FALSE on error so you can check for that.
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Btw: You might want to remove the # operator before mysql_query so you see if something goes wrong there.

Remove error suppression (#) in your code and use inspection methods print_r($var) and var_dump($var) to verify the returned database call values.

Related

Warning: mysqli_fetch_array() expects parameter 2 to be long, object given in

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 )

MySQL fetch row and undefined variable error

I keep getting the following errors. The $query produces a 1300 result list. When I run echo $query I get the following MySQL error:
[25-Aug-2016 21:38:32 America/New_York] PHP Warning: mysql_fetch_row() expects parameter 1 to be resource, null given in song.php on line 285
[25-Aug-2016 21:38:32 America/New_York] PHP Notice: Undefined variable: song_hash in song.php on line 292
$query = "select " . $query_data . " from " . $query_tables . " where " . $query_where;
//echo $query;
$result = mysql_query($query,$database);
while($row = mysql_fetch_row($result)){
$key = $row[0];
$song_hash[$key] = ($song_hash[$key] + 1);
}
$largest = max($song_hash);
In order to help you the contents of $query_data, $query_tables and $query_where needed. You can also print the error with mysql_error(). More likely you will be able to find out the solution from that output.
http://php.net/mysql_error
when you run echo query and you get those errors it simply means you don't have a query..
try hardcoding the query for debugging,
also you need to initialize your song_hash array

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

SQL call keeps on returning error

The SQL call below keeps returning:
Fatal error: Call to a member function fetch_assoc() on a non-object in /home/content/76/10930776/html/apprentice/report.php on line 86
$sql = "select sum(".$column.") as totalmeetings,username from data where datediff(max(dateinput),min(dateinput)) <= ".$daysdifference." group by username ";
echo $sql;
$result = $mysqli->query($sql);
while($pcresult = $result->fetch_assoc())//line 86
{
}
What am i doing wrong?
The SQL call prints out like this:
select sum(prospects1stmeeting) as totalmeetings,username from data where datediff(max(dateinput),min(dateinput)) <= 500 group by username
try this query
select sum(prospects1stmeeting) as totalmeetings,username from data
group by username
having datediff(max(dateinput),min(dateinput)) <= 500
Look at how you're trying to access the results:
$result = $mysqli->query($sql);
while($pcresult = $result_percentile->fetch_assoc())//line 86
{
}
$result and $results_percentile are not the same thing. You should try:
$result = $mysqli->query($sql);
while($pcresult = $result->fetch_assoc())//line 86
{
}
unless you're not showing your whole code.
EDIT
But since you edited your question to no longer reflect this answer, the answer is still that you're trying to access a non object. That means $result does not produce data that can be read as an associative array.

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
I'm having a problem with this mysql code. I presume its a basic error in the $sqlx... line but I'm slightly lost.
The code basically prints messages from a db
Here is the code:
$sqls="SELECT username FROM social WHERE `adder`='$username'";
$results=mysql_query($sqls);
$resulti= mysql_num_rows($results);
if ($resulti==0) {
echo "You haven't added anyone yet. Find some suggestions";
}
$row=mysql_fetch_array($results);
$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";
$resultx= mysql_query($sqlx);
$resultz= mysql_num_rows($resultx);
if ($resultz==0){
echo "No messages at all!!";
}
else {
$finished="false";
$r=0;
While(($rowx=mysql_fetch_assoc($resultx))&&($finished=="false")) {
//echo off messages
$username is got further up the file.
Here is the error:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/user/public_html/social/iframe/index.php on line 34
Line 34 is $resultz= mysql_num_rows($resultx);
But like i said the error is probably the line two up from that.
One interesting happens. "No messages at all!!" is echoed out which means the result of the mysql_query is 0. This is why I am convinced it is the line 32, ($sqlx)
Any idea??
Have I done the mysql_fetch_array wrong when getting $row??
thanks
$row=mysql_fetch_array($results);
$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";
This will create the following query:
SELECT * FROM messages WHERE `sender` IN (Array)
This is obviously not a valid MySQL query. You have to process the array.
$sqlx = "SELECT * FROM `messages` WHERE `sender` IN ("; // start of query
foreach($row as $r)
$sqlx .= "'".$r['username']."',"; // insert all returned usernames
$sqlx = substr($sqlx,0,-1).')'; // substract the last comma and close the query
Or, as RiaD pointed out in the comments:
$sqlx = "SELECT * FROM `messages` WHERE `sender` IN (".
implode(',',array_map(function($x){return "'".$x['username']."'"; }, $row)).
")";
PS: Riad, it should be $x['username'] instead of $x and you forgot the semicolon ;)
mysql_query($sqlx) return false instead of result. It means any error occured. Try to check is $sqlx correct query and check mysql_error() to get what error is occured. To check was here any error or not you can use
if(!$resultx){
print 'error:'.mysql_error();
}
else{
//use result
}
If your query fails mysql_query($sqlx) returns false rather than resource. So, you need to check, that this function returned true (e.g. if (!results) {}) nad print use mysql_error() to see what error was.
if(!$resultx){
print 'error:'.mysql_error();
}
Also, you are embedding $row variable into the query string. But this var is an Array, so you end up with a query like this:
SELECT * FROM messages WHERE `sender` IN (Array)
See mysql_fetch_array manual for details

Categories