If i create an array from results returned in a mysqli query is there a way to select and use only one specific row from the array?
$info= array();
while($row = mysqli_fetch_assoc($query)) {
$info[] = array(
'id' => $row['id'],
'location' => $row['location']
);
}
How would i go about displaying only a single row from this array where the id equals a variable like $id?
In your loop you could just do something like:
if ($id == $row['id']) {
$info[] = $row;
}
However it would make more sense to me to just update your query.
SELECT cols FROM t1 WHERE id = :id
Using $id as a parameter.
Related
I made a function in a CI model that first queries for the table to get its fields(because these fields will change dynamically over time,so I can't hard code a list of field names),and then when it gets the results of the first query, and builds a fields name list,it queries the table again to get the values belonging to one row or record.It then stores the second query result in an array,which is passed back to the controller.Here is the complete function that performs these steps:
public function getAssetFeatures($as_id)
{
$data = array();
//this sql query gets the field names from the table I want to query.
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".DATABASE."' AND TABLE_NAME = 'as_features';";
$query = $this->db->query($sql);
$count = 0;
foreach($query->result_array() as $k)
{
foreach($k as $kk=>$v)
{
if( $v != "as_features_id" &&
$v != "as_id" &&
$v != "cid" &&
$v != "lot_size" )
{
$features_array[$count] = $v;
$count++;
}
}
}
$features_string = implode(",",$features_array);
//I got the field names, put them into an array, then concatenated them into a string, which I will use for the fields in the next query:
$sql = "SELECT $features_string FROM as_features WHERE as_id='$as_id'";
$query = $this->db->query($sql);
//mandatory rooms/features:
foreach($query->result() as $row)
{
foreach($row as $k=>$v)
{
$data["$k"] = $v; //build an associative array with the values of each field for the one row I am querying
}
}
return $data; // return the associative array.
}
At first I thought something was broken in my table or view,but as I kept repeating the same call to the model function by refreshing the page and entering the exact same values,I noticed that sometimes the code worked,and I wouldn't get the errors "undefined index".
So I outputted the results of the array with this code:
echo "<pre>";
print_r($asset['features']);
echo "</pre>";
...and the expected output, which only performs successfully sometimes, but not all the time, for the exact same operation using the exact same parameters, looks like this:
Array
(
[kitchen] => 1
[liv_area] => 0
[dining] => 1
[family] => 0
[bed] => 0
[bath] => 1
[half_bath] => 0
[parking] => 0
[car_storage] => 0
[pool] => 0
[miscellaneous] => 0
)
When the query returns a result set and then a populated array,my form works and looks normal.but,most of the time the query fails,and I get what looks like this:
The issue is with the following snippet of code:
foreach($query->result() as $row)
{
foreach($row as $k=>$v)
{
$data["$k"] = $v; //build an associative array with the values of each field for the one row I am querying
}
}
The way it works is that for every result which is returned it will overwrite $data with the relevant keys. However, because the $query->result() will return the row you want, then return false, the array essentially ends up being:
$data[] = false; i.e., set the whole array to false/empty.
If you change the loop to be, the code inside the loop won't be executed for the false value of $query->result():
while ($row = $query->result())
{
// your code
}
It's worth noting that if you're intending to return more that one row from this, it won't work as it will just overwrite the existing values.
Ok, the problem was my code, not the query. I was passing an encrypted as_id, but neglected to unencrypt it before constructing the select query. That's why it would work sometimes, and not others. For some reason MySQL allowed the encrypted as_id to match existing as_id of INT type. After performing the decrypt, the query results became predictable. This is something I wouldn't expect SO members to have divined. Thanks.
public function getAssetFeatures($as_id)
{
$as_id = $this->utilityclass->decryption9($as_id); // <- I had this commented out. In fact, I removed the line from my example code in the original post, because I didn't think it was important to the question. Not only was it important, it was the problem!
$data = array();
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".DATABASE."' AND TABLE_NAME = 'as_features';";
$query = $this->db->query($sql);
I am basically trying to fetch results from a SQL database and load that into a multidimensional array so i can use them later on in the page.
while($row = mysqli_fetch_array($result))
{
$send = array
(
array($row['Name'],$row['Email'],$row['Mobile'])
);
$count = $count + 1;
}
That is what i am using to get the results which if i print within the while loop it will echo all the results. However when putting it into the array it loads each result into the array as the first result. My initial plan was to use a counting variable to set where in the array the result was set to with this adding by one each time. I am not certain how to specify where to add the result i thought something along the lines of
$send = array[$count]
(
array.....
so i could then refer to the results as 0 to count length but i am not sure how to make this work. Or ,which i presume, if there is a much easier and better way of going about it. I am also not sure if this is necessary as surely the results seem to be in an array when gathered from the SQL database but i am unsure if this array is populated with each while loop or stored and can be accessed at any point
If any one can give me an example of something similar or point me at some documentation much appreciated
Try this:
$count = 0;
while ($row = mysqli_fetch_array($result)) {
$send[$count] = array($row['Name'], $row['Email'], $row['Mobile']);
$count++;
}
I have a better way for you. You could also use the id for your index, if you have one:
while ($row = mysqli_fetch_array($result)) {
$send[$row['id']] = array(
"Name" => $row['Name'],
"Email" => $row['Email'],
"Mobile" => $row['Mobile']
);
}
You can use:
$count = 0;
while($row = mysqli_fetch_array($result))
{
$send[$count] = $row;
$count ++;
}
Also you might want to use the table id as an array index, so you can access the records by ID later. In that case you can do:
while($row = mysqli_fetch_array($result))
{
$send[$row['id']] = $row;
}
You're declaring your array inside your loop. So it will reset it every time.
$send = array();
while($row = mysqli_fetch_array($result))
{
$send[] = array($row['Name'],$row['Email'],$row['Mobile']);
}
Hello guys I have seen a code with $row['columnname'].The code is
$myQuery = "SELECT * FROM information_schema.columns WHERE table_name = '$tabname'";
$re = mysql_query($myQuery);
while($row = mysql_fetch_array ($re)){
if(!empty ($row)){
$col_name = $row['COLUMN_NAME'];
$myQuery = "SELECT ".$col_name." FROM ".$tabname." WHERE sampleid='".$sid."'";
echo "<br>".$myQuery;
$reqq = mysql_query($myQuery);
$roww = mysql_fetch_array($reqq);
echo "<br>".$roww[$col_name];
}
}
My question is what is the use of $row[] in php?
Is it used to embed the column value like $row['columnname'] or just adding a variable like $row[$anyvariable].
That is called bracket notation. $row is an array, which has properties. In this case, it has named properties, so it is an associative array. An associate array has key/value pairs. It looks like this:
$myArray = [
'key' => 'value'
];
To echo the value of the property above, you would use echo $myArray['key'];
In the specific code you included, the property name is "COLUMN_NAME" and it has a value. The code assigns that value to the variable $col_name.
Here's another sample usage to help clarify all of this:
$people = [
'Susan' => [
'Age' => 24,
'Phone' => '555-123-4567'
],
'Jack' => [
'Age' => 27,
'Phone' => '555-9876-5432'
]
];
echo $people['Jack']['Age']; // 27
while($row = mysql_fetch_array ($re)){
This statement loops over all the rows returned in your result set $re and while looping, on every iteration you will get the current row as an array in your variable named $row, this name can be anything, it doesn't have to be $row necessarily.
Then
$col_name = $row['COLUMN_NAME'];
Is just reading $row as an array and picking up the value for the key COLUMN_NAME. This will be one of the columns that were returned by your query for each row of the result set. This also can be any name depending upon your query.
it is from mysql_fetch_array
it returns result array if your query/result was found, if not just FALSE instead
Like it says on the PHP site :
mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
It's not variables that would go inside the $row[] , it's the column name that you have called in your SELECT query .
In your case, you have a SELECT query to return all the columns of a table. 'COLUMN_NAME' is in fact really the name of a column in the table of information_schema.column
mysql_fetch_array returns an array,
$row = [
'column_name' => 'column_value'
]
so the statement
$row = mysql_fetch_array ($re))
will fetches the column names from information_schema.columns that will be stored into $col_name.
$col_name = $row['COLUMN_NAME'];
for more read mysql_fetch_array
I am trying to select multiple rows from the database and then separate the rows into array values so I can use them throughout my code.
This is what I have right now...
$result = mysql_query("SELECT url, image, placement FROM advert
WHERE user='1'") or die(mysql_error());
//This grabs 3 rows with placement name equal to 'sideadtop','sideadmiddle','sideadbottom'
($row = mysql_fetch_array($result, MYSQL_NUM));
$keytop = array_search('sideadtop', $row);
$sideadtop['url'] == $row[$keytop]['url'];
$sideadtop['image'] == $row[$keytop]['image'];
$keymiddle = array_search('sideadmiddle', $row);
$sideadmiddle['url'] == $row[$keymiddle]['url'];
$sideadmiddle['image'] == $row[$keymiddle]['image'];
I am trying to get the url and image values for each ad placement value. I am not sure how the output for the mysql query is sent to php. Is it sent as a multideminsional array or just a array?
Should I be calling individual MySQL queries or is there an easy way to call multiple rows and than separate them after?
mysql_fetch_* will only fetch one row. I think what you want is this:
$result = mysql_query("SELECT url, image, placement FROM advert WHERE user='1'")
or die(mysql_error());
$adverts = array();
while(($row = mysql_fetch_assoc($result))) {
$adverts[$row['placement']] = $row;
}
It will create an array like this:
Array(
'sideadtop' => Array(
'url' => ...,
'image' => ...,
'placement' => ...
),
'sideadmiddle' => Array(...),
'sideadbottom' => Array(...)
)
You can access the individual adverts with $adverts['sideadtop'], $adverts['sideadmiddle'], etc.
Imo this is a better approach than creating a variable for each element.
Calling mysql_fetch_assoc/mysql_fetch_array will get you one row of the data. You can then iterate this, to get all the rows.
I would tend to use mysql_fetch_assoc, for a small performance increase.
E.g.
$result = mysql_query("SELECT url, image, placement FROM advert
WHERE user='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$keytop[] = array_search('sideadtop', $row);
$sideadtop['url'][] == $row[$keytop]['url'];
$sideadtop['image'][] == $row[$keytop]['image'];
$keymiddle[] = array_search('sideadmiddle', $row);
$sideadmiddle['url'][] == $row[$keymiddle]['url'];
$sideadmiddle['image'][] == $row[$keymiddle]['image'];
}
I would also think about how you would like the resulting data structured, but you should get the gist.
I got a database with 2 fields: amount and name.
I want to get all the data from the database (40 rows) and create an associated array out of it like this:
$arr = array("amount" => "12", "name" => "John");
How is this done dynamically in PHP? I am stuck.
If you're using the mysql_* function, you can do the following to get one row at a time:
$res = mysql_query("SELECT amount, name FROM mytable");
while ($row = mysql_fetch_assoc($res)) {
var_export($row); // outputs array ( 'amount' => '12', 'name' => 'John', )
}
To get all rows in a single array:
$customers = array();
$res = mysql_query("SELECT amount, name FROM customers");
while ($row = mysql_fetch_assoc($res)) {
$customers[] = $row;
}
Well, if you run your query, e.g.
$result = mysql_query('SELECT amount, name FROM table');
you can loop over the result like that:
$values = array();
while(($row = mysql_fetch_assoc($result))) {
$values[] = $row;//$row will be like array("amount" => "12", "name" => "John")
}
and you will have an array of arrays.
Check out mysql_fetch_assoc if you want to fetch database rows as an associative array (the documentation comes with a good example, too).
$data = $pdo->query('SELECT amount, name FROM ...')->fetchAll(PDO::FETCH_ASSOC);
That's it in PDO. And if you're not using PDO, well, that's your problem then...