here's my php code
$result = mysql_query("select * from backup where owner='$email'") or die (mysql_error());
$dataCount = mysql_num_rows($result);
$row = mysql_fetch_array($result);
echo json_encode($row);
and it returns this:
{"0":"1","id":"1","1":"2015","year":"2015","2":"55","necessities":"55","3":"10","savings":"10","4":"10","entertainment":"10"}
this is how jsonviewer.stack.hu shows it
fyi, there's only one row of data inside the table. but it seems json_encode($row) displays the value twice, but firstly using number (0 - 4) as the label, then it uses the column name (id, year, necessities, savings, entertainment) as the label.
how can I make it to display the value only once, using the column name?
Change mysql_fetch_array to mysql_fetch_assoc.
mysql_fetch_array returns a result row in both numeric and associative array.
mysql_fetch_assoc returns a result row as associative array.
http://php.net/manual/en/function.mysql-fetch-array.php
You can give this functional additional arguments including MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH. In your case you want MYSQL_ASSOC.
However, you should be using mysqli and not mysql. the mysql functions are no longer maintained.
http://php.net/manual/en/mysqli-result.fetch-array.php
For new versions of php ( > 5.5), use mysqli_fetch_assoc instead of mysql_fetch_assoc.
The mysql_fetch_assoc function is deprecated and is no longer maintained: Using it will lead to errors.
Related
good morning,
i need some help. am using mysql_fetch_row(), which gets a single record from a result set as an indexed array (one that refers to elements by numbers). but i cant get any value passed into my variable
//get the total number of images
$getTotal = "SELECT COUNT(*) FROM images";
$total = mysql_query($getTotal);
$rows = mysql_fetch_assoc($total);
$totalPix = $rows[0];
am trying to get an element or single recored passed into my variable totalPix, is there any other way of achieving this.
thanks you
Change your query to
$getTotal = "SELECT COUNT(*) AS Total FROM images";
and
$totalPix = $rows['Total'];
since you are using mysql_fetch_assoc that returns an associative array that corresponds to the fetched row.
Also you should move to mysqli or PDO
mysql_* extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide
Your $rows is going to contain an array of fields returned, even if it's just COUNT(*).
Try:
$totalPix = $rows['COUNT(*)'];
... or name your COUNT in your query:
SELECT COUNT(*) as totalcount FROM images
...
$totalPix = $rows['totalcount'];
--edit-- removed 0 from assoc array return
Well, an associative array isn't numeric. So using the 0 index won't work.
You'll want to use $rows['COUNT(*)'] since you're using that query.
I have 2 columns in a table called Points. The 2 columns are UserPoints and UserID.
I want to be able to echo the total amount of points a user has.
I've got something like this but I dont think its right.
$getTotalPoints = mysql_query("SELECT SUM(UserPoints) FROM `Points` WHERE `UserID` = '1'") or die(mysql_error());
$totalPoints = mysql_fetch_array($getTotalPoints);
When i echo the above statement by echoing "$totalPoints" i get "Array".
Anyone know the correct query to do this ?
You're getting Array because that's what's stored in $totalPoints. Look closely at your code and you'll see you used the mysql_fetch_array() function, which retrieves a row of results from the results set as an array. If you do var_dump() on $totalPoints you'll see the following:
Array
(
[0] => 12345
[SUM(UserPoints)] => 12345
)
The sum you're looking for is at index 0 or the column name, in this case SUM(UserPoints), so you can output it using echo $totalPoints[0] or echo $totalPoints['SUM(UserPoints)'].
Alternatively, you could use the mysql_result() function. I think this is more in-line with the behavior you were expecting. It fetches a single value from the row from the result set. So, instead of mysql_fetch_array() you'd wrote:
$totalPoints = mysql_result($result, 0);
For more information on mysql_result(), check out the PHP documentation for it.
As an aside, I would recommend not using mysql_* functions if you have the option. A newer interface like PDO, or at least mysqli, would be better. This will depend on your project of course... if you're working with a large legacy code base it may be difficult to change. But if you're starting out now, I think you'd benefit from the newer libraries. You can see my opinion and some guidance on transitioning extensions in this article I wrote.
Hope this helped... and good luck!
mysql_fetch_array fetches a result row as an associative array, a numeric array, or both. by default it creates both. all that you need is to echo $totalPoints[0];
or, if you rewrite you request as
$getTotalPoints = mysql_query("SELECT SUM(UserPoints) total FROM `Points`
WHERE `UserID` = '1'") or die(mysql_error());
$totalPoints = mysql_fetch_array($getTotalPoints);
echo $totalPoints['total'];
mysql_fetch_array returns an array. Therefore you need to treat $totalpoints as an array.
try adding this line to the end of your snippet:
echo $totalPoints[0];
There are several ways to retrieve data with the mysql functions I suggest reading about them in the php manual.
Here is mysql_fetch_array
The resultset row is an array with as many elements as you got in the SELECT.
In you case you only got 1 element (the sum).
So you should:
echo $totalPoints[0];
If you need to debug this kind of issues I recommend you to read about print_r function.
I have a simple mysql query checking the database table 'all_users' for an e-mail which was entered in a text field.
The e-mail is in a variable called $email.
In my test case, $email is something#yahoo.com and that e-mail exists in the database table.
When I do this:
$result=mysql_query("select * from all_users where email='$email' ") or die (mysql_error());
$row=mysql_fetch_array($result);
$num=mysql_num_rows($result);
$num is zero even though $row is found.
So when I do echo $row['email']; it correctly prints out 'something#yahoo.com' but when I do echo $num; it's 0!
What am I doing wrong here? I've done this a thousand times but never had this issue.
From http://php.net/manual/en/function.mysql-fetch-array.php - Returns an array that corresponds to the fetched row and moves the internal data pointer ahead
So change the order, i.e. first use mysql_num_rows and only then do mysql_fetch_array
If you reverse the order of the statements, it will work as you expect. You are retrieving the row from the resource before asking it how many rows it has left. Since you are evidently only finding one row, this results in 0, because you have already retrieved that row.
If you do this it should work:
$num = mysql_num_rows($result);
$row = mysql_fetch_array($result);
I think it's not because of your mysqli_num_rows function, do check the search query, whether it's working or not, otherwise use trim(column_name) instead of simply giving column.
It worked for me... it tooks me 2 days to verify it😜
I have the following code and it only works when I specify the column number!
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
echo($row[0]);
}
Not when I use the name though
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
echo($row['name']);
}
Is there something that needs setting on the MYSQL box?
You might want to try print_r( $row ) for debugging so you see which column names are actually set in the resultset. Getting the associative names doesn't need to be configured in some way, but the index names need to exactly represent the column names in the database result.
mysql_fetch_array, according to the documentation, fetches the result row as an numeric array or as an associative array, depending on the second parameter. By default, this is MYSQL_BOTH, so you can access via both means.
It seems like the problem may like with your query, specifically the actual name of the column in your SELECT statement. Without seeing more of your query, I can suggest adding AS name to the first column to ensure it is the actual retrieved column name. print_r will print the array for further debugging.
The functions are all very similar:
mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_object()
I have recently started using mysql_fetch_object as I am doing alot more OOP with PHP.
But what are peoples opinions on which one is best to use and why, and maybe which scenario they are best to be used in.
Thanks for your thoughts!
mysql_fetch_array will get you an array that can have as keys :
both numbers and names of columns, if using MYSQL_BOTH
columns names, using MYSQL_ASSOC -- in this case, you'll get the same thing you get when using mysql_fetch_assoc
only numbers (depending on the order of columns in the query), if using MYSQL_NUM
Getting results indexed by columns names is probably the most useful solution -- easier to use, at least.
But getting results indexed by the positions of the fields in the select clause is interesting in one situtation : when you have several columns that have the same name or alias.
In this case, as you cannot have two entries with the same index in an array, you will be able to access only one of those columns using the column name as index.
For the other columns that have the same name, you'll have to use numeric indexes.
That situation is probably the only case for which I would use mysql_fetch_array -- and I rather prefer using aliases in my query, to avoid that situation -- it's more clear, in my opinion.
mysql_fetch_assoc will get you an array, with columns names as keys, and data as values.
Not much to say, actually.
And mysql_fetch_object will get you objetcs in return.
Choosing between mysql_fetch_assoc and mysql_fetch_object most probably depend on how you develop your application : if using objects everywhere, the second one is probably the most suited.
If using arrays as data-containers, you can just go with the first one.
mysql_fetch_array() fetches a result row as an associative array, a numeric array, or both.
It returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how $result_type is defined.
By using MYSQL_NUM, you only get number indices (as $row[0], $row1, etc) i.e., numeric array.
By using MYSQL_ASSOC, you only get associative indices (as $row["id"], $row["name"], etc) i.e., associative array.
By using MYSQL_BOTH (default), you’ll get an array with both associative and number indices. (as $row[0], $row["name"], etc) i.e., both numeric array and associative array.
mysql_fetch_assoc() fetches a result row as an associative array. (column names as key).
mysql_fetch_object() fetches the result row as an object.
It returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.
To me there are adantages of using
mysql_fetch_assoc() in that you can use the array functions such as
array_walk and uasort().
Suppose we have following table
Name CountryCode
----- ----------
Bangladesh BD
Pueblo USA
Arvada USA
$query = "SELECT Name, CountryCode FROM City";
$result = mysqli_query($connection, $query)
mysqli_fetch_object (data can be fetch as object)
while ($obj = mysqli_fetch_object($result)) {
printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
}
mysqli_fetch_assoc (fetch as associative array i.e. key)
while ($row = mysqli_fetch_assoc($result)) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
mysqli_fetch_array (numeric & associative both)
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
printf("%s (%s)\n", $row[0], $row[1]);
}
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
Short description:
mysql_fetch_assoc() : This gets you an associative array of data.
mysql_fetch_array() : This returns a combination array of associative elements as well as data with numerical index.
mysql_fetch_object() : Returns an object with properties that correspond to the fetched row.
Source