MYSQL Select rows in PHP by name - php

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.

Related

Pull All Column Names from SQLEXPRESS and insert into PHP Array

I am trying to use INFORMATION_SCHEMA.COLUMNS to get a list of all the columns available in a SQLEXPRESS table. This is the relevant code below:
$getColumns = sqlsrv_query($conn, $columnQuery);
while ($row = sqlsrv_fetch_array($getColumns)) {
echo $row[0];
}
Here are the results from that code:
GUIDFromServerRecTypeProfileNameActionTimeOccurredUserNameUserLDAPNameTSStationTSRemoteAddrUserSIDIPv4FromIPv6FromisDirectorywasBlockedACEtypeFullFilePathShareNameFileNameOnlyNewPathNameSIDOfNewOwnerACLObjectLDAPNameACLObjectDomainACLObjectNameACLMaskACLFlagsACLObjectType
It is the column names I need, but they are all in a single string rather than broken up 1 column per entry in the array the way I need it. I figured this much out by reseaching on this site, but no one mentioned in those other questions that this was a problem.

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.

Error in Comparing the same column in mysql

I am fetching the values from the column as the value of integer and doing this for two user so i tried to get the value from the table and compare it but unfortunately for both greater and smaller comparsion i am getting the same result nothing changed.
How do i compare the column values?
My code is like below-----
$sqlres="select membership from register where mid='".$_SESSION['mid']."' ";
$pres=mysql_query($sqlres);
$prest=mysql_fetch_array($pres);
$sqlres1="select membership from register where matri_id='".$row['mtr_id']."' ";
$pres1=mysql_query($sqlres);
$prest1=mysql_fetch_array($pres);
if($pres<$pres1)
{
//somethiung enter code here
}
First of all don't use mysql_* it is deprecated, use mysqli_* or PDO instead.
As for your question, mysql_fetch_array as the name suggests, returns an array, not a single value, so you need to get the first value in the array:
if($pres[0]<$pres1[0])
{
//somethiung enter code here
}
You save the result in $prest and $prest1 (with "t"), not in $pres and $pres1. I suggest always using the variable $query for the query string and $result for the result table. Only when you fetch the result should you use a custom variable name to not get confused.
You can use something like
if($prest['membership']<$prest1['membership']){//do stuff here}
In the piece of code that you provided, you are comparing the resources that mysql_query returned not the values of the columns. You have to do this:
if( $prest['membership'] < $prest1['membership'] ){
//Some stuff going here
}
Advice: Name your variables properly. Use more describing names. After 2 months you won't remember the difference between $prest and $prest1

mysql check columns?

Is there a way to check what columns are there in mysql syntax?
For example,
$dbh = $db->query("SELECT * FROM table");
while($row = $dbh->fetchAll(PDO::FETCH_ASSOC))
{
$row['somecolumn'];
}
For instance, if there is or not somecolumn, I would like to find out if there is a way that will display a list of ALL the columns in the syntax I'm looking for in table
This way in the future, I'll be able to check if there is $row['fr'] or $row['food'] that can work.
Thanks
You could simply check whether $row contains the key you need.
The PHP function array_key_exists will tell you whether $row contains the key you want. For instance, array_key_exists("fr", $row) will return true if $row contains an fr key.
If you want to see all the keys (i.e. all the columns), simply use array_keys; for example : array_keys($row) will give you all the keys in $row.
Alternatively, if you don't mind another SQL call, you can use SELECT column_name FROM information_schema.columns WHERE table_name='your_table' as xdazz's answer mentions.
You can use the INFORMATION_SCHEMA to do this, or DESCRIBE.
Take a look at the information_schema columns documentation, or see the describe syntax.
You could use the sql below to select cloumn names for one table.
SELECT
column_name
FROM
information_schema.columns
WHERE
table_name='your_table';

PHP: MySQL Query with fieldname in a var

Little question: With the following code...
<?php
$statement = "SELECT * FROM TABLE";
$query_unfetched = mysql_query($statement);
$query_num = mysql_num_rows($query_unfetched);
if ($query_num !== 1) {
exit;
}
$query_fetched = mysql_fetch_object($query_unfetched);
$fielname = "ID";
echo $query_fetched->$fiedname;
?>
With this code, there is no output, because PHP somehow does not check that in $fieldname is an existing name of a field in the selected Table.
Why doesn't it work, have I made a mistake? Or are there any other ways to select a field whose name is saved in a var?
Thanks for the help!
Instead of using mysql_fetch_object, you could use mysql_fetch_assoc. It will return the result as an array, after which you can simply use your variable as a key.
I'd suggest using var_dump on the $query_fetched. Some OS's and DB's will return different capitalizations. Oracle, for one, will always return the column names as capital. I've seen MySQL only return lower in one circumstance.
You can also use the fetch_assoc as suggested by Cpt. eMco and that will give you warnings if the array key is not set. (Remember to turn warnings off in production though).
(I do need to put in an obligatory plug for the PDO classes. I find them far more intuitive and clearer.)

Categories