I did a SELECT query on MySQL and get this as result.
The problem is how can I remove the 2nd duplicated results at for instance we use the 1st item in the list. "0":"1" is a duplicate for "id":"1" I would rather use "id" instead of "0" as the key later on the the app. How could I remove this to simplify the results. I do notice that the "0" means the 1st column as the successive columns does add up by 1.
Here's the $query I run.
SELECT id FROM clubsinformation WHERE :comparisonTime < updateTime
This is caused by most likely the fetching mode, you need to fetch it by associative indices only because right now you're including both associative and numeric index fetching:
No matter what DB API you got, MySQLi or PDO, just set it to associative.
So that it turn it doesn't include the numeric indices, only the column names as keys:
So this would roughly look like in code (from looking at your query placeholders, it seems PDO, so I'll draft a PDO example):
$data = array(); // container
$query = 'SELECT * FROM clubsinformation WHERE :comparisonTime < updateTime';
$select = $db->prepare($query);
$select->bindValue(':comparisonTime', $comparisonTime);
$select->execute();
while($row = $select->fetch(PDO::FETCH_ASSOC)) { // associative
$data[] = $row; // only includes column names
}
// then finally, encode
echo json_encode($data);
// OR SIMPLY
// $data = $select->fetchAll(PDO::FETCH_ASSOC); // associative
// echo json_encode($data);
That fetching is by way of PDO API. If you're using MySQLi you can still use the basic idea.
Related
$q = "SELECT * FROM user";
$res = mysqli_query($conn, $q) or die(mysql_error());
$userList = "";
while($user = mysqli_fetch_array($res))
{
$userList .= $user['userList'].";;";
}
echo $userList;
I don't understand the while part:
Why assign the mysqli_fetch_array to $user using while?
How can the $user have index of userList?
Why concatenate with ;;?
To answer your questions:
i) mysqli_fetch_array() has two possible return values. It either returns an array of the current row that the database result set pointer points to, then advances the pointer to the next row, or it returns false if you have reached the end of the result set. The while() evaluates the value that is set to $row either continuing the loop if it is an array or stopping the loop if $row equals false
ii) The $user array has both numerical indexes for each field (i.e. 0,1,2,... [#fields - 1]) and associative indexes of the column names for the table (i.e. 'field1', 'field2', etc.). In this case one of the fields in the database is userList, so accessing $user['userList'] returns that column value for the row being worked with. BNote that the query itself would have beeter been written as SELECT userList FROM user since that is the only field you are interested in. There is no reason whatsoever to select and transfer all field data if you have no need for it. It is also rarely useful to use just mysqli_fetch_array(), as you rarely need both numerical and associative indexes on the record.It is usually best to specifically request ther associative or numerical array result depending on which you need.
iii) This code is simply building a string rather than an array of results which might be more common. For whatever reason the code writer decided values in the string should be separated by ;;.
I'm getting this column in this bd
$result = mysql_query("SELECT short FROM textos");
and I'm trying to echo only one of the results based on the array it returns:
$col = mysql_fetch_assoc($result);
echo "<b>Short:</b>".$col[1]."<br/>";
apparently this $col array can't be accessed this way. How should it be done? Thanks
That has been already stated in comments above, so just a bit of explanation here.
mysql_fetch_assoc retrieves a result row for you presented as an associative array (an array where keys are field names and values are field values). Your query returns only one field (which is short), but still it doesn't make your row a single scalar value - it remains an array, only with a single element.
So you need to refer it as $row['short'], or in your sample $col['short'].
Bear in mind that query might return no results - you can learn that by checking if the returned value is not an array but scalar false instead, e.g.
if ($col === false) {
echo 'Error occured<br/>';
} else {
echo "<b>Short:</b>".$col['short']."<br/>";
}
Putting LIMIT into your query like again comments suggest is a good idea as well because you wouldn't be returning potentially huge amount of data when you only need one row actually. The result would still come as a multi-dimensional array though, so that part won't change.
To access the first element use $col[0]['short'].
If you only want to output one element anyways you can add LIMIT 1 to the MySQL query.
After querying you should check if the result array is set otherwise php will throw an error saying that $col[0]['short'] is not set.
There are three mysql_fetch functions which getting rows:
mysql_fetch_array() Fetch an array with both indexes (numeric and associative)
mysql_fetch_num() Fetch an array with numeric indexes
mysql_fetch_assoc() Fetch an array with associative indexes
In your example you will get an array that is looking like this one for the function mysql_fetch_array():
array(2) {
[0]=>
string(3) "foo"
["short"]=>
string(3) "foo"
}
$statement = 'SELECT short FROM textos';
$result = mysql_result($statement);
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
var_dump($row); // or echo "<b>Short:</b>".$row['short']."<br/>"; or something else you like to do with rows of the above statement
}
}
I want to do a query in my model from a table known as jurisdictions. Now I want this query to provide a valid MySQL result resource. I.e I want to pass the result to mysql_fetch_array(). If I pass in $query = $this->db->query(). I get an error saying that the passed in argument is invalid. I was wondering how can I convert $query to a MySQL result recource.
Well, if you want to have a MySQL resource, you should be using mysql_query.
Codeigniter already has a method which will give you one row at a time: row_array (actually, it has two, the other is just row, but that returns an object, not an array). If you want to get numeric indexes on the result of result_array, use array_values:
$result = $this->db->query( "SELECT 'foo' as foo_rules FROM DUAL" );
$aso_arr = $result->row_array(); // assoc. array w/o numeric indexes
echo $aso_arr[ 'foo_rules' ];
$num_arr = array_values( $aso_arr );
echo $num_arr[ 0 ];
If you would like the entire result of the selection, then use result and result_array (they have behavior similar to row and row_array, only they return the whole result set in an array)
EDIT
I repeat my first sentence, but you can get the MySQL resource this way:
$result = $this->db->query( "SELECT 'foo' as foo_rules FROM DUAL" );
$resource = $result->result_id;
But, since this is not documented, it should not be considered supported or even expected behavior. Be forewarned.
If I'm understanding you correctly then why not just use the available methods of:
$query->result();
or
$query->result_array();
Choose whichever to suit your needs.
can any one know the, convert mysql query in to an php array:
this is mysql query :
SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC
I want to convert this query in to simple php array .
So, you need to get data out of MySQL. The best way, hands down, to fetch data from MySQL using PHP is PDO, a cross-database access interface.
So, first let's connect.
// Let's make sure that any errors cause an Exception.
// <http://www.php.net/manual/en/pdo.error-handling.php>
PDO::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// We need some credentials...
$user = 'username';
$pass = 'password';
$host = 'hostname';
$dbname = 'database';
// PDO wants a "data source name," made up of those credentials.
// <http://www.php.net/manual/en/ref.pdo-mysql.connection.php>
$dsn = "mysql:host={$host};dbname={$dbname}";
$pdo = new PDO($dsn, $user, $pass);
There, we've connected. Let's pretend that $sql has the SQL you provided in your question. Let's run the SQL:
$statement = $pdo->prepare($sql);
$statement->execute();
There, it's been executed. Let's talk about results. You steadfastly refuse to tell us how you want your data structured, so let's go through four ways that you could get your data.
Let's first assume that the query returns a single row. If you want a numerically indexed array, you would do this:
// <http://www.php.net/manual/en/pdostatement.fetch.php>
$array = $statement->fetch(PDO::FETCH_NUM);
unset($statement);
If you want an associative array with the column names as the keys, you would do this:
$array = $statement->fetch(PDO::FETCH_ASSOC);
unset($statement);
Now, what if the query returns more than one record? If we want each row in a numerically indexed array, with each row as an associative array, we would do this:
// <http://www.php.net/manual/en/pdostatement.fetchall.php>
$array = $statement->fetchAll(PDO::FETCH_ASSOC);
unset($statement);
What if we want each row as a numerically indexed array instead? Can you guess?
$array = $statement->fetchAll(PDO::FETCH_NUM);
unset($statement);
Tada. You now know how to query MySQL using the modern PDO interface and get your results as no less than four types of array. There's a tremendous number of other cool things that you can do in PDO with very minimal effort. Just follow the links to the manual pages, which I have quite intentionally not linked for you.
This over-the-top post has been brought to you by the letters T, F and W, and the number PHP_MAX_INT + 1.
i don't get you clearly, but
mysql_fetch_array and mysql_fetch_assoc
both returns only array
please refer:-
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/en/function.mysql-fetch-assoc.php
If you just need a simple array...
while ($row = mysql_fetch_array($query)) { //you can assume rest of the code, right?
$result[$row['url_id']] = array($row['sumtime']);
}
For a simple array
$sql = mysql_query("SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC");
while($row = mysql_fetch_array($sql)){
$array1 = $row['sumtime'];
$array2 = $row['title'];
$array3 = $row['url'];
}
Hope this is one you wanted
Dude the fastest way is probably the following
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row;
}
print_r($data);
I'm using PHP ADOdb and I can get the result set:
$result = &$db->Execute($query);
How do I get the field names from that one row and loop through it?
(I'm using access database if that matters.)
It will depend on your fetch mode - if you setFetchMode to ADODB_FETCH_NUM (probably the default) each row contains a flat array of columns. If you setFetchMode to ADODB_FETCH_ASSOC you get an associative array where you can access each value by a key. The following is taken from ADODB documentation - http://phplens.com/lens/adodb/docs-adodb.htm#ex1
$db->SetFetchMode(ADODB_FETCH_NUM);
$rs1 = $db->Execute('select * from table');
$db->SetFetchMode(ADODB_FETCH_ASSOC);
$rs2 = $db->Execute('select * from table');
print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1')
print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')
To loop through a set of results:
$result = &$db->Execute($query);
foreach ($result as $row) {
print_r($row);
}
Small improvement to the solution posted by #thetaiko.
If you are ONLY needing the field names, append LIMIT 1 to the end of your select statement (as shown below). This will tell the server to send you a single row with column names, rather than sending you the entire table.
SELECT * FROM table LIMIT 1;
I'm working with a table that contains 9.1M records, so this minor change speeds up the query significantly!
This is a function I use to return a field array - I've stripped out some extra stuff that, for example, allows it to work with other DBs than MySQL.
function getFieldNames($strTable, $cn) {
$aRet = array();
# Get Field Names:
$lngCountFields = 0;
$strSQL = "SELECT * FROM $strTable LIMIT 1;";
$rs = $cn->Execute($strSQL)
or die("Error in query: \n$strSQL\n" . $cn->ErrorMsg());
if (!$rs->EOF) {
for ($i = 0; $i < $rs->FieldCount(); $i++) {
$fld = $rs->FetchField($i);
$aRet[$lngCountFields] = $fld->name;
$lngCountFields++;
}
}
$rs->Close();
$rs = null;
return $aRet;
}
Edit: just to point out that, as I say, I've stripped out some extra stuff, and the EOF check is therefore no longer necessary in the above, reduced version.
I initally tried to use MetaColumnNames, but it gave differing results in VisualPHPUnit and actual site, while running from the same server, so eventually
I ended up doing something like this:
$sql = "select column_name, column_key, column_default, data_type, table_name, table_schema from information_schema.columns";
$sql .= ' where table_name="'.$table.'" and table_schema="'.$database_name.'"';
$result = $conn->Execute($sql);
while($row = $result->fetchRow()) {
$out[] = strToUpper($row['column_name']);
}
I think it should work with mysql, mssql and postgres.
The benefit of doing it like this, is that you can get the column names, even if a query from a table returns an empty set.
If you need the Coloumn names even for empty tables or for joins about multiple tables use this:
$db->Execute("SELECT .......");
// FieldTypesArray - Reads ColoumnInfo from Result, even for Joins
$colInfo = $res->FieldTypesArray();
$colNames = array();
foreach($colInfo as $info) $colNames[] = $info->name;
The OP is asking for a list of fieldnames that would result of executing an sql statement stored in $query.
Using $result->fetchRow(), even with fetch mode set to associative, will return nothing if no records match the criteria set by $query. The $result->fields array would also be empty and would give no information for getting the fieldnames list.
Actually, we don't know what's inside the $query statement. Besides, setting limit to 1 may not compatible with all database drivers supported by PHP ADOdb.
Answer by Radon8472 is the right one, but the correct code could be:
$result = $db->Execute($query);
// FieldTypesArray - an array of ADOFieldObject Objects
// read from $result, even for empty sets or when
// using * as field list.
$colInfo = [];
if (is_subclass_of($result, 'ADORecordSet')){
foreach ($result->FieldTypesArray() as $info) {
$colInfo[] = $info->name;
}
}
I have the habit of checking the class name of $result, for as PHP ADOdb will return false if execution fails.