PHP MYSQL CASE substitution in array [duplicate] - php

This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 8 years ago.
Morning all, happy new year!
I am trying to select all records within a MYSQL database into an array where 1 column matches a list, and then replace the output of the cells when selected from that column.
It's a sports table, and I have the Positions as MF, DF, CF and want to replace them with Midfield, Defence, and Forward respectively.
I was hoping that the following would crack it, but get an error message, which lines up to the FROM line:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/peterborough/www/www/wp-content/plugins/insert-php/insert_php.php(48) : eval()’d code on line 14
$result = mysql_query("SELECT *,
CASE Position
WHEN 'DF' THEN 'Defence'
WHEN 'MF' THEN 'Midfield'
WHEN 'CF' THEN 'Forward'
FROM People
WHERE
(Position='DF' or
Position='MF' or
Position='CF') and
Season = '2014'
ORDER BY Number");
while($row = mysql_fetch_assoc($result)){...}
Thanks guys

you have a syntax error in your SQL:
the CASE expression requires an END
SELECT *,
CASE Position
WHEN 'DF' THEN 'Defence'
WHEN 'MF' THEN 'Midfield'
WHEN 'CF' THEN 'Forward'
END AS position_long
FROM People
WHERE
(Position='DF' or
Position='MF' or
Position='CF') and
Season = '2014'
ORDER BY Number
Explanation:
when the syntax error hits, you get a FALSE from the mysql_query() call and
when that's passed into mysql_fetch_assoc() it complains about being given a boolean instead of a resource

Related

Array converted to int [duplicate]

This question already has an answer here:
Why SUM of column values return 1?
(1 answer)
Closed 9 days ago.
I have a problem, I need to convert from an array to a full number, but I don't understand how. i`m using redbeanphp. Help please
print_r(R::getRow('SELECT SUM(view) FROM posts WHERE author LIKE ? LIMIT 1', ['dffdfghdfgdf']));
Result:
Array ( [SUM(view)] => 27 )
if through echo, then it simply gives an error that it is an array.
Result:
Warning: Array to string conversion in
You should print the value of the array element, not the array itself.
Also, you may use an alias for a result column using the as operator.
$result = R::getRow('SELECT SUM(view) as s FROM posts WHERE author LIKE ? LIMIT 1', ['dffdfghdfgdf']);
print_r($result['s']);
echo would work either in this case.

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

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"];
}

use an array of unknown length in where clause of mysql [duplicate]

This question already has answers here:
Opposite of MySQL FIND_IN_SET
(6 answers)
MySQL, PHP: Select * from table where id is not in array
(3 answers)
Select all field where field value not in array
(3 answers)
Closed 3 years ago.
I am writing an SQL query. I have an array of unknown length and I want to select the data fromMySQL by using that array in the WHERE clause of the query. This is my query right now and it is working fine
$sql = "SELECT DISTINCT messagesutou.SenderID from messagesutou where (messagesutou.SenderID !='$items[1]' AND messagesutou.SenderID !='$items[0]' AND messagesutou.SenderID !='$items[2]') AND messagesutou.RecieverID='$uid'";
But in this I know the length of array ( 3) and I just used the array name with index for testing purpose. Now i want to know if array length is unknown then how would I write this query?
$list = implode(',', $items);
and
SELECT DISTINCT SenderID
FROM messagesutou
WHERE 0 = FIND_IN_SET(SenderID, '$list')
AND RecieverID='$uid'
or (taken from Jens's answer which was deleted by him)
SELECT DISTINCT SenderID
FROM messagesutou
WHERE SenderID NOT IN ($list)
AND RecieverID='$uid'
The difference - both variants are applicable when SenderID and $items values have a numeric type, only the former when they have string type, none when they have string type and contain commas or ticks.
But the latter may be adapted:
$list = '\''.implode('\',\'', $items).'\'';
and
SELECT DISTINCT SenderID
FROM messagesutou
WHERE SenderID NOT IN ($list)
AND RecieverID='$uid'
It now acccepts any datatype and allows commas (but not ticks - they must be quoted before imploding).

Why can I not store booleans in a php array?

Why can't I store a boolean in an array? I get an error when I attempt to run it. (On line line 3)
The columns being retrieved with the exception of stamp are booleans. Here's a snippet of my code.
$BoolQ = "SELECT stamp, active, latvian, russianSpeaker FROM tasktable WHERE taskID=usrid;";
$Boolr = mysqli_query($connection,$BoolQ);
$Boolrow = mysqli_fetch_array($Boolr);
Error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
In the 3rd line of the code: $Boolrow = mysqli_fetch_array($BoolQ); , shouldn't you be using $Boolr as the parameter instead of $BoolQ? If that's a typo, which most probably it is, the result of mysqli_query is false, probably an issue with connection or the query.

mysqli subquery string didn't works [duplicate]

This question already has answers here:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given [duplicate]
(2 answers)
Closed 8 years ago.
I have a mysql query which doesn't work. It gives me the following error:
mysqli_query() expects parameter 1 to be mysqli, null given
my sql query is:
$select = mysqli_query($sql, "SELECT title FROM category WHERE id LIKE (SELECT categorie_id FROM categories_sub WHERE file LIKE '".$site."')")
The query will not work, what your query is doing
WHERE id LIKE (SELECT categorie_id FROM categories_sub WHERE file = 'some val')
This is similar as
WHERE id = {multiple categorie_id}
when the subquery has more than one categorie_id and this will return error.
So replace
category WHERE id LIKE
to
category WHERE id IN ( ...
This error tends to mean that you didn't connect correctly to the database. Double check your connection. Also, file LIKE 'x' is equivalent to file='x'. To search for a string containing 'x', use file LIKE '%x%'.
Edit: The other answers are right that you need to use IN instead of LIKE for the first one (i.e. a member of the set defined on another query)

Categories