Sort mysql result in php - php

When I use the following code:
$result = queryMysql("SELECT * FROM games ORDER BY game ASC");
$num = $result->num_rows;
for ($j = 0 ; $j < $num ; ++$j)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
}
the result is not shown alphabetically. it has Destiny first, and Battlefield last. Destiny has ID 1, and Battlefield has ID 11.
Why isn´t it being sorted? If I use the command in PhpMyAdmin I get the list back sorted.
(Sorry if this is too simple, but I didn´t find any solutions here. All refered to use ORDER BY, but that´s not working).
New code changed to:
$result = queryMysql("SELECT * FROM games ORDER BY game ASC");
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
}
Still not working. Could this be a server error?
Not sure what happened here, but after 8 hours of sleep and I reload the page, it´s sorting as it should (still using Maximus2012´s example).
I guess it must have been a server glitch, since I didn´t change the code while sleeping.
I´ll give creds to Maximus2012 for his quick and good responds!
(and thanks to all others too ofcourse!)

Replace this :
$num = $result->num_rows;
for ($j = 0 ; $j < $num ; ++$j)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
}
with this: (get rid of $num and the for loop)
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
}
and see if that works. You don't need for loop since you are not using the $j variable anywhere anyway. This answer is based on the assumption that your MySQL query is giving you correct result.

It looks like you are sorting by whatever your first field game rather than the field that actually contains the name of your game (can't tell what that is from the information given).
Just sort the proper field.

Run SET NAMES utf8; Be sure you have collation utf8_general_ci in your table and field. Check that field game has character set utf8
Then run this query just before your own query and see if this helps.
function queryMysql($query)
{
global $connection;
$connection->query("SET NAMES utf8");
$result = $connection->query($query);
if (!$result) die($connection->error);
return $result;
}

Related

Why is my MySQL search query returning column names and data?

I'm fairly new to PHP and I've been stumped on this issue for a while now (been searching everywhere but no help really).
I'm attempting to search for all the data in a data table ("Select * FROM X") and that seems to work fine.
However when I try to return/echo the data, encoding into JSON format as an array (I'd like 1 row as 1 index in the array) it does wierd things.
Heres the code I currently use;
$SQL = "SELECT * FROM `units`";
$Result = mysqli_query($link, $SQL) or die ("DB ERROR");
$Total = mysqli_num_rows($Result);
if($Total > 0)
{
$rows = mysqli_fetch_array($Result, MYSQLI_NUM);
$row_count = mysqli_num_rows($Result);
while($row = mysqli_fetch_array($Result))
{
echo json_encode(array($row));
}
}
This then gets used in Unity (C#) via;
JSONObject obj = new JSONObject(loadUnitsWWW.text);
Debug.Log(obj);
The results of which are;
[{"0":"2", "unitID":"2","1":"Tanks","unitName":"Tanks","2":"Ground","unitType":"Ground"},[],[],[],[],[],[],[],[],[],[],[]]
it seems to be trying to return EVERYTHING for some reason, including the column names. But I've no idea why it'd return the same results multiple times (and no idea where the 0 came from).
As I said, I'm fairly inexperienced with PHP, as such its very likely something (in fact I'm certain) something is wrong with that code, I've tried a for loop such as;
for($i = 0; $i < $row_count; $i++) {...}
but to no avail (it returns something like:
["1",[],[],"",null,null,null,{},null,null,null.null[],""..........]
Heres the data table layout if it helps;
unitID | unitName | unitType
1 | infantry | Ground <br>
2 | Tanks | Ground <br>
3 | Support | Ground <br>
4 | Artillery | Ground <br>
. <br>
.
There are 13 items in the table
EDIT:
THis is what I am expecting:
[["1", "Infantry","Ground"],["2","Tank","Ground"]....]
Here is how you should be doing this. comment in code
// Always use the field names. this is going to avoid debug nightmare later.
$SQL = "SELECT unitID, unitName, unitType FROM `units`";
$Result = mysqli_query($link, $SQL) or die ("DB ERROR");
$Total = mysqli_num_rows($Result);
if($Total > 0)
{
// initilize a new array
$data = array();
// Note use mysqli_fetch_row because you want only result values
while($row = mysqli_fetch_row($Result))
{
// add the row data to our array
$data[] = $row;
}
// encode the entire data and echo
echo json_encode($data);
}
Reference : mysqli_fetch_row
Edit: you can also do this like the following.
if($Total > 0)
{
// Get all the result at once and json_encode it!!
echo json_encode(mysqli_fetch_all($Result));
}
Reference: mysqli_fetch_all
Edit2: as per #YourCommonSense comment your code can be
$SQL = "SELECT unitID, unitName, unitType FROM `units`";
if ($Result = mysqli_query($link, $SQL))
{
echo json_encode(mysqli_fetch_all($Result));
} else die ("DB ERROR");
There are 2 issues with your php snippet:
if you look at the mysqli_fetch_array documentation, you'll notice that if you don't supply the second int $resulttype argument, it defaults to MYSQLI_BOTH; this means that both associative and numeric indices will be returned
you call mysqli_fetch_array on $Result twice, first assigning it to $rows variable, and second time inside the while condition assigning it to the $row variable
I'm guessing what you want to do is:
remove the $rows assignment
inside the while condition add the 2nd argument MYSQLI_NUM
0 refers to column order in the result set. You can refer to mysqli-result.fetch_array and check parameters and return type.
change your line:
while($row = mysqli_fetch_array($Result))
with:
while($row = $rows) {
// your code
$rows = mysqli_fetch_array($Result, MYSQLI_NUM);
}
Another solution, I think it is better for you
$rows = mysqli_fetch_all($Result, MYSQLI_NUM);
echo json_encode($rows);

array access won't increment in php mysql

I'm trying to update the first column in a table with new values, using something like what I've got below..
the problem is that the $userTemp variable is not incrementing in mysql but it seems to run through the elements in an array (as expected) within a php for loop. however in mysql_query this does not seem to be reflecting? I don't quite understand why as when I echo $userTemp before the mysql_query it shows that it is incrementing correctly. the query is run through the function queryMysqlPopulate($userTemp,$row[0]); but the argument does not seem to get passed to the function. however after the function call running another echo for $userTemp shows that the value has infact incremented.
like seriously?! please could someone enlighten me as to why? does session control have something to do with this?
any help is greatly appreciated!
PS. this is not the full program I've just snipped the parts that are applicable, so as not to take up too much of your time (hope that helps).
$userlogins = array('c001','d001','dj001','ed001',
'k001','nr001','ol001','pt001',
'py001','rx001','s005');
if (tableExists('mytable'))
{
$tempQuery = queryMysql("SELECT username FROM students");
$numRows = mysql_num_rows($tempQuery);
for ($j = 0 ; $j < $numRows ; ++$j)
{
$userTemp = "$userlogins[$j]";
echo $userTemp;
$row = mysql_fetch_row($tempQuery);
queryMysqlPopulate($userTemp,$row[0]);
echo $userTemp;
}
}
and the function
function queryMysqlPopulate($tempLogin, $tempRow){
$result = mysql_query("UPDATE mytable SET username='$tempLogin' WHERE username='$tempRow'") or die(mysql_error());
return $result;}
i can't answer my own question cause i#M a newbie :P
so edit insteaD:
No problems this works fine, although it's not exactly what i was looking for as it's not exactly array access, but explicitly referring to a field by it's value :(
for($i = 0; $i < $loops; ++$i)
{
queryMysql("INSERT INTO $name VALUES" .
"('hi$i', 'there', 'all', 'you', 'cats')");
}
then changing update ...set to
if (tableExists('mytable'))
{
$tempQuery = queryMysql("SELECT username FROM mytable");
$numRows = mysql_num_rows($tempQuery);
for ($j = 0 ; $j < $numRows ; ++$j)
{
$userTemp = "$userlogins[$j]";
echo $userTemp;
$row = mysql_fetch_row($tempQuery);
queryMysqlPopulate($userTemp,'hi'.$j);
echo $userTemp;
//echo $row[0];
}
//echo tableExists('none');
}
I'd still prefer to do this by array access i.e. accessing the first field of the first column by element number in the update ... set mysql query. so any help with that is greatly appreciated.

Echo whole table without using column names as ref

Hi I really hope someone can help,
I have a table with one row and multiple column names, one of these being id, I want to echo the whole table without using the column names as reference as these might change and I don’t want to have to go in and change the code if a column gets added or taken away. i.e. I want to SELECT * from table WHERE id=1 then echo the whole table, not including the id column or any column titles.
I’m a bit stumped and not sure where to look for the right answer, hopefully someone can point me in the right direction.
Thanks in advance being trying to get my head around this all weekend.
Brill thanks for all the help got it sorted, for anyone who wants my solution:
$sql = "SELECT * from nav WHERE id='1'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$i=1;
while($i<=500)
{
echo $row[$i] . "<br />";
$i++;
}
Use mysqli_result::fetch_row instead of mysqli_result::fetch_array as it will return an indexed array of values.
Example:
$result = $mysqli->query($query)
$columns = $mysqli->field_count;
while($row = $result->fetch_row()) {
for($i = 5; $i < $columns; ++$i)
echo $row[$i] . ", ";
echo "\n";
}
Edit: updated to start from column 5 as requested in comments
SELECT id AS no_title, column1 AS ... FROM table WHERE id=1
I don't see your point why you want to do this, but you can always choose an alias, I haven't tried AS " " yet, though...

Query Result: What is $row[0]

I know this may sound like a stupid question from a programming-newbie, but I just want to make sure I understand correctly.
After a query, what does $row[0] stand for/ result in?
Is my understanding correct that $row[0] shows ALL results?
HERE ARE EXAMPLES:
$query = "SELECT count(commentid) from comments where jokeid = $jokeid";
$result = mysql_query($query);
$row=mysql_fetch_array($result);
if ($row[0] == 0)
{
echo "No comments posted yet. \n";
} else
{
echo $row[0] . "\n";
echo " comments posted. \n";
AND THIS ONE
$query = "Select count(prodid) from products where catid = $catid";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if ($row[0] == 0)
{
echo "<h2><br>Sorry, there are no products in this category</h2>\n";
}
else
{
$totrecords = $row[0];
Thanks in advance.
$row[0] will simply echo the first column in your database.
0 is the first because all arrays in PHP (and in most programming languages) are zero-based - they simply start with zero.
$row[0] will be the value of the first column in your results. If you use mysql_fetch_assoc($result) you will have an array in the form:
array(column_name => column_value);
e.g.
$row = mysql_fetch_asssoc($result);
$value_column_1 = $row['column_1'];
You can also use mysql_fetch_object($result) to get an object with column names as the parameters.
$row = mysql_fetch_object($result);
$value = $row->column_name
mysql_fetch_array() takes the next (in your examples first) row out of the resultset and stores the data in an array $row.
$row[0] now represents the first value of that row.
So in total in your examples the variable holds the first value of the first row of your resultset.

MYSQL - Select specific value from a fetched array

I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;

Categories