Good day,
I am trying to create a form that will search for results in mysql DB and display the results using a loop. I have two options for searching, one using the ID and one using a string.The ID search works fine, as ID's are unique and one result is return which I can print out, but I am trying to adapt this to a function I can use for both, as the string should return a list results which will need to be looped through. The result is being returned as an object, and this is where I am struggling to get the loop to give a list of attributes and keys for each result, as it loops for each key=>Value fine, but need to know how to go through each object first, then the key=>Value.
In my class this is the find code i am using:
public static function find_by_qual_id($qual_id){
global $database;
$clean_qual_id = $database->escape_value($qual_id);
$result_array = static::find_by_sql("SELECT * FROM sdp WHERE qual_id='{$clean_qual_id}' LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
return $result_array;
}
On the page this is the loop (which does not work):
if(isset($qual_id)){
$qual_info = Qual_lookup::find_by_qual_id($search_qual_id);
if($qual_info != null){
echo "<h4>RESULTS FOUND FOR \"{$search_qual_id}\"</h4>";
echo "<div><form name=\"found_qual\"><table>";
foreach($qual_info as $qual){
foreach($qual as $key => $value){
echo "<tr><td>{$key} : </td><td">{$value}</td></tr>";
}
}
} else {
echo "No results found for \"{$search_qual_id}\"";
}
echo "</table></form></div>";
}
OK I found the problem... for some reason I have 2 return statements in the class:
return !empty($result_array) ? array_shift($result_array) : false;
return $result_array;
removing the first return statement now makes this work... it seems.
Related
I'm trying to build a complicate query where there is an unknown number of postalcode areas posted to my api. At the moment I almost found the solution, but I can't concatenate my whereBetween parameters to the Query in the scope. I get the error query can't be casted to string, which also makes sense.
The array passed to the scope has the following structure: $plz = [[10000, 11000], [34200, 34500]];
Here is my code in the scope:
public function scopePlz($query, $plz)
{
$queryString = '';
foreach ($plz as $index => $single) {
$queryString .=
$index == 0
? "->whereBetween('postalcode_int', [$single[0], $single[1]])"
: "->orWhereBetween('postalcode_int', [$single[0], $single[1]])";
}
return $query . $queryString;
}
You could solve it like this:
public function scopePlz($query, $plz)
{
$first = array_shift($plz);
$query->whereBetween('postalcode_int', [$first[0], $first[1]]);
foreach ($plz as $single) {
$query->orWhereBetween('postalcode_int', [$single[0], $single[1]]);
}
return $query;
}
Get the first item from the array, add it like a where and then run the rest of the array through a foreach.
If you want one big where statement for all these postal codes, wrap this scope in an separate where method.
I have My code Below. I have a function "getdet" that return array of record,but i cant able to print the all records the codes displaying only the first records may time. Pls help to solve this issue.
<?php
function getdet($qry){
global $con;
$Selecting=mysqli_query($con,$qry);
$Fetch=mysqli_fetch_array($Selecting);
return $Fetch;
}
$qry="SELECT * FROM `tbs_employee` WHERE EmpId='1' limit 1";
$GetData=getdet($qry);
$i=0;
while($GetData){
echo $i."-".$GetData['EmpId'].":".$GetData['EmpName']."<br>";
$i++;
}
?>
Below is my Table
Here is my result
0-1:Fst Employee
1-1:Fst Employee
2-1:Fst Employee
3-1:Fst Employee
4-1:Fst Employee
5-1:Fst Employee
6-1:Fst Employee
.
.
.
infinity
You are running the same query ($Selecting=mysqli_query($con,$qry);) over and over again inside your getDet-Function, so it will never quit the while-loop:
while($GetData){
Should be:
$qry="SELECT * FROM `tbs_employee` WHERE EmpId='1' limit 1";
$Selecting=mysqli_query($con,$qry);
$i=0;
while($GetData = mysqli_fetch_array($Selecting)){
echo $i."-".$GetData['EmpId'].":".$GetData['EmpName']."<br>";
$i++;
}
mysqli_fetch_array will return null, if all results are returned, then the while-loop can exit.
Well, your function only return a data. Here's the right way:
<?php
function getdet($qry){
global $con;
$Selecting=mysqli_query($con,$qry);
while($row=mysqli_fetch_array($Selecting, MYSQLI_ASSOC)){
$Fetch[] = $row;
}
return $Fetch;
}
$qry="SELECT * FROM `tbs_employee`";
$GetData=getdet($qry);
foreach($GetData as $i=>$row){
echo $i."-".$row['EmpId'].":".$row['EmpName']."<br/>";
}
?>
In your query you filtered employers by the ID
WHERE EmpId='1' limit 1
If you wants to get all records, delete this statement.
The reason this happens, is because you have created an endless loop. The way you use it, is the same as 'true', small example:
$example = 'some value';
if ($example) {
echo 'You will see this echo!';
}
If we now take it one step further; you have a while loop. But the way you use it now, is as above. In other words it's always true:
$example = 'some value';
while ($example) {
echo 'You will see this echo! At least untill the server runs out of resources';
}
What you have, is that you set $GetData before the loop. This way, after the loop has run one itteration, the value does not change. You only set it's value before the while, so you never move to the next line!
Luckily, the solution is very simple. We need to assign it every itteration. The following snippet is a common way to do it:
while($GetData = getdet($qry)){
// Now, after every run, we set $GetData to the next line
}
The last run, the mysqli_fetch_array function returns null, so your function does too, so the while loop stops.
Offtopic: We have a few coding standards which make reading code easier. One of them is indentation; as you can see, my code reads easier. This is because I use 4 spaces (1 tab) in an if-statement for example. I strongly recommend you do this too (possible start with editting your topic here).
I'm kinda new to Laravel, and I'm wondering how I can check for a specific value in the databse? I have 5 different category id's in my databse, and I wanna do a check on the databse and act differently depending on what the category id is.
I'm thinking something like this:
if ($example = Example::where('category_id', '=', '1')->first()) {
echo "The category id is 1";
}
or maybe:
$example = Example::where('category_id', '=', Input::get('category_id'))->first();
if ($example === 1) {
echo "The category id is 1";
}
I also tried other things, based on what I already have working, but cannot seam to get this feature to work.
You can use firstOrFail() method of Laravel like this:
$example = Example::where('category_id', '=', '1')->firstOrFail();
if ($example) {
echo "The category id is {$example->id}";
}
return "error";
The firstOrFail methods will retrieve the first result of the query;
however, if no result is found, a
Illuminate\Database\Eloquent\ModelNotFoundException will be thrown
UPDATE:
For fetching and checking each rows, use all() method and iterate through each rows to get your desired results.
$examples = Example::all();
foreach($examples as $example) {
if ($example->category_id == 1) {
echo "echo here the 1 thing....";
} elseif($example->category_id == 2) {
echo "echo here the 2 thing....";
} else {
echo "something else"
}
}
Hope this helps!
I have a function that I loop to to build an url. what I need is to get the result in a single string. This is the code.
// Create URL for accesories
function create_url($id) {
global $db_categories;
// Select category sublevels
$sql_cat="SELECT parent_id, seo_id FROM $db_categories WHERE category_id = '".$id."'";
$catres = mysql_query("$sql_cat") or die (mysql_error());
while($selected_cat = mysql_fetch_array($catres)) {
$cat_seo = $selected_cat['seo_id']. "/";
$output .= $cat_seo;
create_url($selected_cat['parent_id']);
}
return $output;
}
// Call function
$result_cat = create_url($cat["category_id"]);
echo $result_cat;
This work fine if I use echo and will output (I only use $depth to track the results)
category1/
category2/
category3/
etc...
The problem is that I don't know how to return the result into a single string instead of echo it. When I use return it only outputs the first result. like this.
category1/
I want the return to output.
category1/category2/category3/
I can't for my life find a solution for this.
Thank's
Example: my current result set:
array(7) {[0]=>array(2)
{ ["class_id"]=>string(1) "1"["class"]=>string(3)"1st"}
{ ["class_id"]=>string(1) "2"["class"]=>string(3)"2nd"}
{ ["class_id"]=>string(1) "3"["class"]=>string(3)"3rd"}
I want a new result set as :
array(7) {[0]=>array(2)
{ ["new_id"]=>string(1) "1"["new_class"]=>string(3)"1st"}
{ ["new_id"]=>string(1) "2"["new_class"]=>string(3)"2nd"}
{ ["new_id"]=>string(1) "3"["new_class"]=>string(3)"3rd"}
I dont want this to affect the column names in my database. only the result set.
Show us your query.. If you're doing, for example, the following query:
SELECT class_id, class FROM table;
Change it to this:
SELECT class_id AS new_id, class AS new_class FROM table;
Changing it in the query is hands-down the best way to do it, as you're not having to do any extra work within PHP, however you could also amend them in PHP, of course.
// where $resultset is your original results..
foreach ($resultset as &$result) {
$result_ = array('new_id' => $result['class_id'], 'new_class' => $result['class']);
$result = $result_;
}
Note that neither of these methods would affect your database columns. The only way to do that would be via an ALTER|MODIFY TABLE statement.
try this
function rename_key(&$array, $oldkey, $newkey) {
// remember here we send value by reference using `&`
if(array_key_exists($oldkey,$array))
{
$array[$newkey] = &$array[$oldkey];
unset($array[$oldkey]);
}
return $array;
}
foreach($input as $k)
{
rename_key($k, 'class_id', 'new_id');
rename_key($k, 'class', 'new_class');
$output[]=$k;
}
echo "<pre>";
print_r ($output);
In foreach cycle. Create a new array with needed to you colums from existing result set.