Getting a single value from an indexed array - php

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.

Related

How do I make execute with PDO output a string rather than a single-element array?

I want to select a field in my mysql database containing values separated by commas (let´s say it´s "dd,bb,ee"), so that these can be exploded and turned into an array.
However, if trying to do this:
$sql = $conn->prepare("SELECT contacts FROM Users WHERE username = ?");
$sql->execute($usernametmp);
$oldcontacts = $sql->fetch(PDO::FETCH_COLUMN);
I get this error:
Warning: PDOStatement::execute() expects parameter 1 to be array, string
given in /.../.../.../.../.../....php
on the execute line, whereas if I do the following:
$sql = $conn->prepare("SELECT contacts FROM Users WHERE username = ?");
$sql->execute(array($usernametmp));
$oldcontacts = $sql->fetch(PDO::FETCH_COLUMN);
it works, but with the db entry coming out as one array element containing "dd,bb,ee", where it´ll need to be a string in order for me to use explode on it with the comma as a delimiter.
Any idea how to fix this?
I believe the PDO fetch function returns an array, not a scalar, even if the row contains a single column.
(I'm not at all familiar with the PDO::FETCH_COLUMN style with the fetch function. Is that documented somewhere? I think that style can be used with the fetchAll function. But that will still return an array.)
The PDO fetchColumn function will return a scalar, rather than an array.
Reference: http://php.net/manual/en/pdostatement.fetchcolumn.php
(And passing bind parameters into the execute is separate unrelated issue.)

how to get the last value from mysql and increment with php

i have a user database and i have to assign a user id for them for example AA01
AND after insert 1 person into database i have to insert another person with user id AA02 AND i have increment it and so on.
what i have already tried is
$sql_user_id=mysql_query("SELECT MAX(user_id) FROM `users` desc LIMIT 1");
$new_array = explode('AA',$sql_user_id);
$number=$new_array[1];
$newnumber=$number+1;
and i am getting wrong with result Resource id #5
You have to fetch the query results before you can use them.
$result=mysql_query("SELECT MAX(user_id) AS maxId FROM `users` desc LIMIT 1");
$sql_user_id = mysql_fetch_assoc($result);
$new_array = explode('AA',$sql_user_id['maxId']);
$number=$new_array[1];
$newnumber=$number+1;
FYI, I added an alias to your query as it makes referencing a value returned from a function much easier to do.
mysql_query() returns a resource, not a value you can operate directly. You have to fetch the value from this resource first:
$res = mysql_query('SELECT MAX(`user_id`) FROM `users`');
$val = mysql_fetch_row($res);
$new_array = explode('AA', $val[0]);
...
Also, notice that MAX() causes an implicit grouping to happen. So there is no order, and there is only one result. Specifying any of this in your query is futile.
In addition, notice that, since user_id is aparently a text, it might not work as expected. When sorting text, 2 comes after 10. You may need to use a different reference to fetch the latest user_id. If you can help it, don't use text to index your records.

echo json_encode($row) returns duplicate values

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.

php odbc result modified after passing as parameter

$out = odbc_exec($connection, $query);
$first = odbc_fetch_array($out);
works just fine
$out = odbc_exec($connection, $query);
$first = odbc_num_rows($out);
works just fine
$out = odbc_exec($connection, $query);
$first = odbc_fetch_array($out);
if(odbc_num_rows($out)) {
//This should execute true, but doesn't
}
To my knowledge, any variable you pass ($out) to a function are only read.
How can calling fetch_array cause num_rows to error?
Update
I've even copied the result straight after the odbc_exec into a 'temp' variable & used that on the fetch_array, yet still it throws. seriously, what the f.
From PHP Manual:
Note: Using odbc_num_rows() to determine the number of rows available
after a SELECT will return -1 with many drivers.
odbc_num_rows method is typically used to detect the number of rows modified by an INSERT, UPDATE, or DELETE call.
If you want the full query returned plus the length, loop through the results using odbc_fetch_array storing them into an array and then determine the number of tuples from the array length.
If you are only wanting to query the number of rows in a given view, then you are better off to write a query that returns a COUNT and fetch that as an array.

Echoing the sum of a table in PHP

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.

Categories