I have an array of the record retrieved from a SQL server database stored in an object $result. I will like to access each item in the array object and print it out to the screen. How can I achieve this? My attempt is below
$result = $DB->get_records_sql("SELECT rawname, ID FROM mdl_tag where tagType = 'institution'");
$result = array();
foreach ($result as $ $value) {
echo $value;
);
}
Here is the correct code:
// Get results from table 'tag', where 'tagtype' matches 'institution', with no sorting and returning fields 'id' and 'rawname'.
$results = $DB->get_records('tag', ['tagtype' => 'institution'], '', 'id, rawname');
foreach ($results as $value) {
echo $value->rawname;
}
So, there are a number of issues:
Use get_records, unless you really need to use get_records_sql.
If you do need to use get_records_sql, then the table is called {tag} not mdl_tag, otherwise you'll run into problems on any server that uses a prefix other than 'mdl_' (e.g. when running phpunit or behat tests).
Writing $result = array(); immediately before looping through the result will throw away the details from the database and replace them with an empty array
The results from get_records (or get_records_sql) are an array containing objects, each of which contains the values for the requested fields, so you need to access the individual value, not try to echo the entire object
All database fields in Moodle are lowercase, so 'tagtype' not 'tagType', 'id' not 'ID'.
Related
I would get Joomla custom fields values from a PHP script. I include all necessary files and I can read checkbox values from "fields" table, the "fieldparams" column.
If I execute this code
$query = "select #__fields.fieldparams from #__fields where #__fields.id = 19";
$db->setQuery($query);
$result = $db->loadRowList();
foreach ($result as $value) {
echo gettype($value); // 01
echo $value[0]; // 02
$var = json_encode($value[0]);
echo gettype($var); // 03
}
the type of $value is "Array" (step 01), so if I access to $value[0] the result (step 02) is the global list (so I suppose this is an Array with 1 element)
{
"options":{
"options0":{"name":"type1","value":"1"},
"options1":{"name":"type2","value":"2"},
"options2":{"name":"type3","value":"3"},
"options3":{"name":"type4","value":"4"},
"options4":{"name":"type5","value":"5"}
}
}
but when I try to use json_encode the result (step 03) is a string.
In this way I can't access to keys and relative values.
What's wrong?
There are 2 issues here. 1. You're using ->loadRowList() which is a method designed to return an array of rows (i.e. multiple rows), not one as is implied by your where clause, and 2. Rather than using PHP's native functions, try using Joomla's JRegistry class instead.
To address these points:
1 Since you're only expecting 1 row to be returned (field with ID 19), replace your line:
$result = $db->loadRowList();
with
$result = $db->loadResult();
$result will contain the fieldparams column only.
2 Create an instance of the JRegistry class so we can access the key => value pairs:
// new registry
$registry = new JRegistry();
$registry->loadString($result); // load the string from the db
// if you need an array, use jregistry's toArray method
$arrayData = $registry->toArray();
Hope it helps,
Gez
I am using in_array function to skip adding the same addresses to an array.
Code:
$addresses_list = array();
$stmt_select_address_result = $databaseManager->connect()->prepare("SELECT lat,lng,address FROM api_order where userid=683;");
$stmt_select_address_result->execute();
while ($row = $stmt_select_address_result->fetch(PDO::FETCH_ASSOC)) {
if (!in_array($row, $addresses_list)) {
array_push($addresses_list, $row);
}
}
I want to skip adding to the arrays if $row['address'] is the same as an address of $addresses_list['address'].
You can create a temporary variable to store the value of address already stored in the $addresses_list array. Whenever, you are storing a $row in the $addresses_list array, you can store the address key value in the temporary variable.
Now, everytime you need to check against the temporary variable, whether the key value already exists or not.
Note that even PHP documentation recommends using [] operator against array_push(). So I have changed your code to use [] instead.
Note: If you use array_push() to add one element to the array, it's
better to use $array[] = because in that way there is no overhead of
calling a function.
Try below (explanation in comments):
$addresses_list = array();
$temp_addresses = array(); // Create a temp array
$stmt_select_address_result = $databaseManager->connect()->prepare("SELECT lat,lng,address FROM api_order where userid=683;");
$stmt_select_address_result->execute();
while ($row = $stmt_select_address_result->fetch(PDO::FETCH_ASSOC)) {
// check in temporary variable instead
if (!in_array($row['address'], $temp_addresses)) {
// add to temp array to avoid duplicate entry in next loop
$temp_addresses[] = $row['address'];
$addresses_list[] = $row;
}
}
If you really want unique address values only, and there is no other use of the duplicate rows. You can rather solve this problem at the SQL query end itself. You can simply use GROUP BY on address. This will optimize the data packet being transferred from database server to PHP application. Moreover, additional array operations can be done way with.
$addresses_list = array();
// It is a good practice to have query string in a separate variable
$sql = "SELECT lat,lng,address
FROM api_order
where userid=683
GROUP BY address;"
$stmt_select_address_result = $databaseManager->connect()->prepare($sql);
$stmt_select_address_result->execute();
while ($row = $stmt_select_address_result->fetch(PDO::FETCH_ASSOC)) {
// No need for any checks, as you are getting unique addresses only
$addresses_list[] = $row;
}
I'm using PDO, and I managed to get the table columns despite the table name and create the bind variables, like in ... VALUES (:foo, :bar);.
The method I'm trying to do this is insert().
public function insert()
{
// the variable names depend on what table is being used at the moment the script runs.
// These methods use the PDO `getColumnMeta()` to retrieve the name of each column
$sql = "INSERT INTO {$this->getTableName()}({$this->getTableColumns()}) "
. "VALUES ({$this->getTableColumns(true)})";
// The previous method gets the name of each column and returns a single string, like "foo, bar, [...]"
// and this function is used to separate each word, with the specified delimiter
$col = explode(", ", $this->getTableColumns());
// Now here lays the problem.
// I already know how to retrieve the columns name as a variable, and
// how to dynamically create the get method, using `ucfirst()`
// What I need would be something like this being inside of a
// loop to retrieve all the separated words from `$col` array.
$data = array(
$col[$i] => "\$this->entity->get".ucfirst($col[$i])."()",
)
/*
* From now on, is what I need to do.
*/
// Lets pretend the column names are "foo, bar".
$data = array(
":foo" => $this->entity->getFoo(),
":bar" => $this->entity->getBar()
)
// That'd be the final array I need, and then continue with
$stm = $this->db->prepare($sql);
$stm->execute($data);
}
You have to loop over $data array and add function as per your requirement.
Fetch values from `... VALUES (:foo, :bar); Then explode as you did in your code , then loop over $col array and add values to $data as required
foreach($col as $val){
$method = "get".ucfirst( $val);
$data[ $val] = call_user_func(array( $this->entity,$method));
}
Above code may work as follow
$data[':foo'] = $this->entity->getFoo();
$data[':bar'] = $this->entity->getBar();
I have written this code which in theory i want to loop round an array and for every value use in a select statement to retrieve the applicable information. Then map a particular value id as a key and the value from the sql statement as its associated value. Though i cant seem to figure out how to add it as a value into my array im sure im a word out.
heres my code
/*
* Loop through the hasNewModelIdInYear and retrieve the exterior media paths
* with a mapped id as a key.
*/
$mediapatharray = array();
foreach ($hasNewModelIdInYear as $key => $value) {
$selectMediaPathFromValue = "SELECT `name` FROM `media` WHERE `id`='".$value['img1_media_id']."'";
$res = $mysqli->query($selectMediaPathFromValue);
$mediapatharray[$value['model_id']] = $res;
}
All that array returns is an array full of keys but no values.. With the variable $res do i then have to ->fetch_value? as im not sure on the syntax needed in order to access the data from the query?
regards mike
it is not good writing whan you have query inside loop. you should search based on array of img1_media_id
you can do follwing
$selectMediaPathFromValue = "SELECT `name` FROM `media`
WHERE `id` IN = '$hasNewModelIdInYear'";
array should be following format
$hasNewModelIdInYear = "12,21,22,65";
The result will return false on failure or the results on success. Mysqli result will be returned the first set of array that consist of the array index. You will need to fetch the values and store it in array. Try adding this code.
while($row = $res->fetch_assoc()){
$mediapatharray[$value['model_id']] = $row['name'];
}
Thanks for your responses i was trying to make it more complicated than it needed to be. I done it by putting the whole media table in a multidimension array then looping through them both and comparing values and if mathcing id map the name.
simple connection and sql query to populate the array, then map the id to a key and name as its value. heres my code.
mediaarray is an array with the media table contents populated in it
$mediaIdPAthFromOld = array();
foreach ($hasNewModelIdInYear as $hnkey => $hsvalue) {
foreach ($mediaarray as $mpavalue) {
if ($hsvalue['img1_media_id'] == $mpavalue['id']) {
$mediaIdPAthFromOld[$hsvalue['model_id']] = $mpavalue['name'];
}
}
}
though this has done what i wanted i assume there is a more effient way to do this.
regards mike
I was talking to a person today who mentioned he used arrays when calling parameters or for other reasons when pulling data from the database etc.
Basically my question is: how would you use arrays in web development?
For example:
If you had a url like this (a social dating site)
http://www.example.com/page.php?sid=1&agefrom=30&ageto=40&sex=female&loccation=los angeles
How I would query the browse page (when showing a list of users) is
$id = mysql_real_escape_string($_GET['id']);
$agefrom = mysql_real_escape_string($_GET['agefrom']);
$ageto = mysql_real_escape_string($_GET['ageto']);
$sex = mysql_real_escape_string($_GET['sex']);
$location = mysql_real_escape_string($_GET['location']);
mysql_query("select from table where id = '$id' and agefrom='$agefrom' [.....the rest of the query]")
Can this be done with arrays? What if a location wasn't selected or the age wasn't entered? If i did the query it might fail.
I hope my question is more clear now.
Arrays make it easy to hold a set of values, or key => value pairs, inside a variable. It also makes it easy to iterate over a set of values.
foreach ($myarray as $key => $value)
{
// do something with this key and value
}
If you are passing a large number of values to a function, and this set of values could be thought of as a list or a lookup table, then you would use an array.
Please consult the PHP manual on arrays for more information.
Edit:
I think I see what you mean now. It can be helpful to sort of 'abstract' your database calls by creating a function that accepts values as an array. For example:
function editrecord($recordid, $values)
{
// SQL is generated by what is in $values, and then query is run
// remember to check keys for validity and escape values properly
}
That's an extreme simplication of course.
Arrays are an important feature of any language, they have O(1) (constant time) random access and can be used as a base data structure to make more complex types.
Specifically talking about PHP, the arrays are used VERY often, the language itself uses them for example to grab the GET and POST parameters.
To get data, you can also make use of arrays in PHP.
You can use mysql_fetch_assoc, this will retch a result row from the database as an associative array, each index of the array will represent a column of data of the current row:
//...
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
// Here, the $row variable is an associative array.
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}