Get the most popular input data input in MySQL with PHP [duplicate] - php

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 1 year ago.
I'm trying to make a website to keep the best time records on my website. Currently I'm struggling to get the most popular levels.
I'm using MySQL in combination with phpMyAdmin (for the manual input) and PHP to manage my tables. Currently I'm using a table recordData to keep track of certain records. The table consists of a uniqueID(int) (A.I.), time(int), timeUsername(varchar) (the player with the time), timeLevelID(int) (the level played) and some other irrelevant data.
What I want is an output of the int data in timeLevelID that got used the most. Please see the following data to simplify this concept:
uniqueID
timeLevelID
1
6
2
2
3
31
4
31
5
6
6
6
Where the desired output is a sorted count table, descending by count data:
timeLevelID
count
6
3
31
2
2
1
What I've tried so far:
First attempt, I tried messing around with the SQL query, but somehow I never got it to work.
require_once "dbConnect.php";
$allRecordsDataSQL="SELECT timeLevelID COUNT(timeLevelID) AS timeLevelIDFrequency FROM recordData GROUP BY timeLevelID ORDER BY timeLevelIDFrequency DESC";
$allRecordsData = $conn->query($allRecordsDataSQL);
print_r($allRecordsData);
while($row=$allRecordsData->fetch_array(MYSQL_ASSOC)){
echo $row["timeLevelID"];
}
This creates the following error, and also doesn't return anything on the print_r - I assume $allRecordsData is false?
Fatal error: Uncaught Error: Call to a member function fetch_array() on boolean
In my second attempt I tried catching all the data in a new array. The new array would count the amount of levels each level has, After which I sort the array and output it's data.
require_once "dbConnect.php";
$allRecordsDataSQL="SELECT timeLevelID FROM recordData";
$allRecordsData = $conn->query($allRecordsDataSQL);
$arrayCounter = array_fill(1, $allRecordsData->num_rows, 0);
while($row = $allRecordsData->fetch_array(MYSQLI_ASSOC)){
$arrayCounter[$row["timeLevelID"]]++;
}
rsort($arrayCounter);
foreach($arrayCounter as $key => $val){
echo "<br>";
echo "$key = $val\n";
}
The second attempt does work PHP wise, but the output is the following, and I've got no clue what to do with this:
0 = 4
1 = 3
2 = 3
3 = 3 ..etc..
I assume my first attempt has a silly mistake but I just can't seem to spot it (I'm new to MySQL & PHP, sorry). Nevertheless, I do think the first attempt is the most efficient so I'd like to solve my issue this way.

You have not included the source code of your dbConnect.php file. It appears to be suppressing the errors which is why you did not get an exception thrown for the error in your SQL query. There's a comma missing after timeLevelID in the SELECT list -
require_once "dbConnect.php";
$allRecordsDataSQL="SELECT timeLevelID, COUNT(timeLevelID) AS timeLevelIDFrequency FROM recordData GROUP BY timeLevelID ORDER BY timeLevelIDFrequency DESC";
$allRecordsData = $conn->query($allRecordsDataSQL);
Using var_dump instead of just print_r will often tell you more (boolean false perhaps) -
var_dump($allRecordsData);
while($row=$allRecordsData->fetch_array(MYSQL_ASSOC)){
echo $row["timeLevelID"];
}

Related

Passing an array to a query using a WHERE clause - works in phpmyadmin, not in my script [duplicate]

This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Closed 12 months ago.
I've searched for the answer online, if I've missed something obvious, I would appreciate links. Otherwise, I'd be grateful for direct help. This is the first time I've ever tried a query like this.
I have the following query:
SELECT * FROM `dice_t` WHERE qty IN (:qty) AND opacity IN (:opacity) AND color IN (:color)
To which I am feeding the following array:
Array
(
[qty] => 1,2
[opacity] => 3
[color] => 467,1007
)
It works perfectly (retrieves 163 rows) in phpMyAdmin (when I type in the values), but in my script, it retrieves only 114 rows, which corresponds to it using only the first value in each field (i.e. qty: 1; opacity: 3; color: 467). I have verified this by running the query with only those values in phpMyAdmin.
My code looks like this:
$statement = $dbConn->prepare($sql);
$statement->execute($queryData);
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
When I print the values of $sql and $queryData I get the values listed in the first two code blocks above.
The fields are all integers. I tried searching with single quotes around the values, but got an error.
I can't figure out what I'm doing wrong.
the Varable :qty is handled as Strinf So you have '1,1'
So you must use FIND_IN_SET
SELECT * FROM `dice_t` WHERE FIND_IN_SET(`qty`,:qty) AND FIND_ON_SET(`opacity`,:opacity) AND FIND_IN_SET(`color`,:color)
other ways are in this thread Can I bind an array to an IN() condition?

Notice: Trying to access array offset on value of type bool in (PHP 7.4.9)

I not much of a coder, I can look and somewhat guess and figure out what's going on and know just enough to make myself dangerous, so please be kind. This was given to me to work on.
I have PHP 7.4.9 installed but the PHP was originally set up in PHP 5. In PHP 5 everything is working fine. In 7.4.9 I am getting the error "Notice: Trying to access array offset on value of type bool in." This page has 9 different arrays pulling from different systems using Oracle. All the arrays work except for the first one has issues. Some keys work and others do not. I found that if i remove those keys it works properly. My thought process is that PHP 5 was more forgiving and skipped over the numbers not pulling data but for each number that is not working i get the same "bool" error.
I want it to go through each key of the array, if the key is not reporting a value do nothing and move to the next key.
Errors with this Array
$L2toMES= array(
"receive_l2" => array (1126,2126,2226,2326,4126,4226,4326,4426,5126,5226,5326)
No Error when numbers are removed
"receive_l2" => array (1126,2226,2326,4226,4326,5226,5326)
The number in the array's are associated with $msgID in the code below and the error occurs 13 lines down , $Img = dangerLevel($msgID, $row['hardTime']);.
foreach ($lastMessage as $tableNm=>$msgNum) {
foreach ($msgNum as $msgID){
//query and obtain the current count at status 0, and the average time in queue (in days, hours and seconds), provided those messages do not have remarks indicating a wait reason.
//obtain the time of the most recent successful message and continue
$row = exeQuery($conn, "SELECT to_char(max($modified), 'dd-mm-yyyy hh24:mi:ss') as \"maxModified\", to_char(to_date('00:00:00','HH24:MI:SS') + (sysdate - max($modified)), 'HH24:MI:SS') as \"timeSince\", to_char(to_date('1','J') + (sysdate - (max($modified))), 'J') - 1 as \"daySince\", ((sysdate - max($modified))*86400) as \"hardTime\" FROM MES.$tableNm WHERE (message_no = $msgID and status = 1 and $created > sysdate - 3/24 and $modified > sysdate - 3/24) group by message_no");
//assess risk for the status bubbles
$Img = dangerLevel($msgID, $row['hardTime']);
printRow($msgID, $Img, $row['timeSince'], $row['daySince']);
Found the resolution - I had to add an if(empty.. after $row = exeQuery;. This basically told the code to continue to the next key in the array if a key did not return a value.
if(empty($row)){
{
continue;
}
return $row;
}

fetch data from mysql table and display [duplicate]

This question already has answers here:
fetch(PDO::FETCH_ASSOC only returning one row
(2 answers)
Closed 3 years ago.
I am trying to fetch image name stored in database and display it but it is not working? Can anyone please tell me what is wrong in below code:
<p class="phase-title-en">
<?php
$title="SELECT DISTINCT record_step_one FROM phase_one_data";
$vartitle=$dbh->prepare($title);
$vartitle->execute();
$result= $vartitle->fetch();
?>
</p>
<?php foreach($result as $fn_title) {
echo "<p> '".$fn_title['record_step_one']."'</p>";
}
?>
My database looks like this:-
Your main problem is that you are using the PDO fetch() method, which returns only the next row of the result set (in your case, the first row).
This way, when you do a foreach, you are actually iterating over the columns of your first row (and not over all the rows, as you intended).
So your code is probably throwing lots of error messages (actually E_NOTICES) telling you that you are trying to use a string as an array, because each of the values in the loop ($fn_title) are strings containing the values for the first row (5, 2, eagle, etc).
EDIT: Sorry, but in my original reply I didn't notice the DISTINCT keyword in your query. So actually, the foreach would run only once, and the value would be the string eagle. But still, the problem is the same, there is no index record_step_one inside the string eagle.
The first step towards your solution would be to replace fetch() with fetchAll(), and check for any other errors that may arise (for instance, we can't see where $dbh is being instantiated in your code, which may or may not be a problem).

PHP echo of SQL query

I've a problem with my code. I can't wrap my head around what's wrong with the code or where I fail.
I basically want to calculate the average of multiple numbers from my database from one column.
/*data calculation*/
$calculation = "SELECT AVG(current) FROM offset_items";
$calculation_result = mysqli_query($connect, $calculation);
if($average = mysqli_fetch_assoc($calculation_result))
{echo "Average: ".$average["current"]."<br>";}
The problem here is, that I get only a blank displayed after the "Average: ".
But if I remove the AVG from the query, I get all results listed of that DB column. The DB contains data, which I import in the same script, as well as displaying them for testing.
I get the following error, which is the line of the echo:
Notice: Undefined index: current in C:\MAMP\htdocs\Offset_Items.php on line 50
I think the problem here is the mysqli_fetch_assoc, but I'm not sure.
Digging through the multiple topics about that "Undefined index" didn't solve my problem. Even when I declare the variable before as NULL.
I'm out of touch with programming, but currently picked it up again to code some tools for work. So if you guys could help me, I would be really thankful.
The PHP code that attempts to print the result reads:
$average = mysqli_fetch_assoc($calculation_result);
echo "Average: ".$average["current"]."<br>";
but the query that generates the result set does not contain any column named current.
Use an alias for the expression AVG(current) in the SELECT clause to get a column in the result set having the desired name:
SELECT AVG(current) AS current FROM offset_items

Using $_GET to get search term, turn array into requested column [duplicate]

This question already has answers here:
fetch single record using PHP PDO and return result
(2 answers)
Closed 6 years ago.
I have not made the change from MySQL_ to PDO until today. Needless to say, the migration is more than a simple headache. So, I need a bit of help. I tried all the search terms I could before registering and asking this question.
My Problem
User types a numeric code into the search box, translates it to
.php?code=term
Script selects all columns from the database where the code is the
code term searched for.
PHP will Echo the results
My Code
if (isset($_GET["code"])) {
//IF USER SEARCHES FOR CODE, RUN THIS. ELSE SKIP.
$crimecode = $_GET["code"];
$crcode = $link->prepare("SELECT * FROM crimecodes WHERE code = :code");
$crcode->bindParam(':code', $crimecode);
$crcode->execute();
$coderesult = $crcode->fetchAll();
echo "<h4>CODE:</h4>";
echo $crimecode;
echo "<br /><h4>DEFINITION:</h4>";
echo $coderesult;
die();
}
Before, it was simple. All I had to do was:
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
But, the ever evolving world has decided to fix something that wasn't broken so now the whole prior code is pointless and you gotta learn something new. Any help is appreciated to get this to work.
Right now, the above PDO code returns definition: ARRAY.
Like literally, the $coderesult prints Array.
The fetchAll() option returns an array containing all of the result set rows (http://php.net/manual/pt_BR/pdostatement.fetchall.php).
$coderesult prints Array because it's actually an array. If you do var_dump($coderesult) you'll see it.
I suppose that you are trying to get one row only. If that's the case, add this line after $coderesult = $crcode->fetchAll();:
$coderesult = $coderesult[0];
Then you can
echo $coderesult['definition'];
If you're trying to get more than one row, you need to use foreach to loop through the array.
I suggest you read the php manual for PDO Class or mysqli, wherever you prefer. There's a lot more options than mysql_.
Also, I think it's worth to mention that your previous code
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
it's vulnerable to SQL Injection.

Categories