PHP MySQLi get the row using foreach - php

I have this function that i created for getting the rows of data from mysqli database.
I try to used foreach but the only i got was something like i attached the image please view.
oops sorry i can't post image it required me 10 reputation to do that.
below :
Yes these is what i got 1 2 x M M n O O X
my codes below with form and php
## FOR SHORTHAND DATABASE
if ( !function_exists( 'hs_debugSQL' ) ) {
function hs_debugSQL($hs_db, $string, $debug=0) {
if ($debug == 1)
print $string;
if ($debug == 2)
error_log($string);
$result = mysqli_query($hs_db, $string);
if ($result == false) {
error_log("SQL error: ".mysqli_error($hs_db)."\n\nOriginal query: $string\n");
// Remove following line from production servers
die("SQL error: ".mysqli_error($hs_db)."\b<br>\n<br>Original query: $string \n<br>\n<br>");
}
return $result;
}
}
## FOR SELECT SQL
if ( !function_exists( 'hs_getrows' ) ) {
function hs_getrows($sql, $debug=0) {
$result = hs_debugSQL($sql, $debug);
if($lst = mysqli_fetch_array($result)) {
mysqli_free_result($result);
return $lst;
}
mysqli_free_result($result);
return false;
}
}
form
<label for="message_title">Send to Admin <span class="red">*</span></label>
<input id="name" name="user_to" class="text" />
<select name="user_to">
<?php
global $hs_db;
$get_list_admin = hs_getrows( $hs_db, "SELECT * FROM hs_users WHERE user_control = 'admin' " );
foreach ( $get_list_admin as $keys ) {
echo '<option value="'.$keys['user_login'].'">'.$keys['user_login'].'</option>';
}
?>
</select>
connection from mysqli is fine as you can see i can get the data from mysqli.
but when i used foreach to retrieve the data it only show 1 number and sometimes 1 character.
i like to learn what is wrong with my codes for foreach.
thank you.

EXPLANATION
The problem is here:
if($lst = mysqli_fetch_array($result)) {
mysqli_free_result($result);
return $lst;
}
mysqli_fetch_array returns row by row, you should loop through the result and returning the array. Something like this
$lst = array();
while ($lst = mysqli_fetch_array($result)){
$lst[] = $row;
}
mysqli_free_result($result);
return $lst;
EDITED:
Well, i see another extrange thing
hs_debugSQL($sql, $debug);
and in the form
hs_getrows( $hs_db,....)
Your are calling the function hs_debugSQL with the SQL you want to execute i guess but in your function the first param is the database link, and the second the SQL you want to execute. You should change this to match the params for the function.
And you are calling the function hs_getrows with the database link in the first param and in function declaration you expect the $sql so you should change this.

I can't help but think that these 'helper' functions are making things more complicated than they should be. There's more than one problem here, but here's a crucial one:
This function:
function hs_debugSQL($hs_db, $string, $debug=0) {
requires $hs_db, a dtabase connection resource, be passed in, while this code:
function hs_getrows($sql, $debug=0) {
$result = hs_debugSQL($sql, $debug); // where is $hs_db?
if($lst = mysqli_fetch_array($result)) {
mysqli_free_result($result);
return $lst;
}
mysqli_free_result($result);
return false;
fails to provide a that key argument. Of course, further up the sequence of calls we find that $hs_db has been submitted, but has now been called $sql and the query seems to be missing.
Simplify! Get rid of these unhelpful functions, clarify what you are trying to do and make something work. Then if you feel the need to encapsulate some of this again, go ahead and do so knowing that the code basically works.

If you want to use a real helper
<?php
$sql = "SELECT user_login FROM hs_users WHERE user_control = 'admin'";
$admin_list = $hs_db->getCol($sql);
?>
<label for="message_title">Send to Admin <span class="red">*</span></label>
<input id="name" name="user_to" class="text" />
<select name="user_to">
<?php foreach ($admin_list as $admin): ?>
<option value="<?=$admin?>"><?=$admin?></option>
<?php endforeach ?>
</select>

Related

Comparison of words from the database and output of the result

I need to check the words received from the database with the user's entered word and if there is a match, then output its value from the database, and if not, then output what the user entered.
The code below works fine if there is a match.
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
}
}
}
}
I'm an amateur in PHP, just learning. And I can't figure out how to output $d_typeplace if no match is found.
I tried to add
else {
echo $d_typeplace;
}
, but I get an array of words from the user entered.
I will be grateful for any help. Also for any suggestions for improving this code.
---Addition---
I apologize for my English. This is a problem in the Russian language, I need to take into account the morphology. To do this, the database has a list of words and their analog, for example, X = Y. I get these words and compare what the user entered. If he entered X, then we output Y. If he led Z, which is not in the database, then we output Z.
Thus, we check $d_typeplace with $d_typeplace_raw and if there is a match, we output $d_typeplace_morf, which is equal to $d_typeplace_raw. And if not, then $d_typeplace (it contains the value that the user entered).
Oh, I'm sorry, I understand myself that I'm explaining stupidly)
I cannot quite understand what you are asking: you need to output the string entered by the user, but you can only print an array?
If this is the case, I think you parsed the string before, in order to therefore you need to do join again the values contained in the array.
Try with:
else {
echo implode(" ", $d_typeplace);
}
--- EDITED ---
Try with:
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
$found = false;
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
$found = true;
break;
}
}
if (!$found) {
echo $d_typeplace;
}
}
}
But I think it would be more efficient, if you implemented the second code snippet written by #Luke.T
I'm presuming you were trying to add the else like this?
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
} else {
echo $d_typeplace;
}
}
}
}
Which was outputting an array because the for loop was continuing, if you add a break like so...
echo $d_typeplace;
break;
It should stop outputting an array. Depending on your use case you could however perform similar functionality directly in your sql query using LIKE ...
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('
SELECT ego_slovoforma_v_predlozhnom_padezhe
FROM dEzpra_jet_cct_tip_mest_obrabotki
WHERE vozmozhnyi_variant_mesta LIKE %' . $d_typeplace . '%');
if ($typeplace_results) {
//Echo result
} else {
echo $d_typeplace;
}
}

How do you make sure an array is empty in PHP?

Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php

How to handle empty array in codeigniter?

So these are my codes.
model
function read() {
$sql= "SELECT * from table WHERE name = 'rabin'";
$query = $this->db->query($sql);
$res = $query->result_array();
return $res;
}
controller
function show() {
$this->load->model("db");
$array['data'] = $this->db->read();
$this->load->view("page", $array);
}
view
foreach($data as $val) {
"<p>" . echo $val['name']; . "</p>"
"<p>" . echo $val['address']; . "</p>"
}
Here, when there are no records in the database satisfying the WHERE clause in the query, the model returns null and I get error saying $data expects parameter 1 to be array, null given. There are several methods to deal with this situation. But, what would be the best possible way to handle this situation ?
The problem is the foreach needs data provided by the database, but you didn't give them anyone.
So I will do this instead:
Model
function read() {
$this->db->where('name', 'rabin');
$res = $this->db->get('table');
return ($res->num_rows() > 0) ? $query->result_array() : false;
}
Controller
function show() {
// $this->(model_name)->(function);
$result = $this->db_model->read();
if ( $result ) {
// if there has data returns, load view
$array['data'] = $result;
$this->load->view('page', $array);
}
else {
// otherwise, show errors.
// you can handle by yourself
echo "no result!";
}
}
Use the Query Builder always to prevent from SQL Injection.
The Model returns the result_array, or false, so that you can handle the result.
Use $res->row_array() instead if your query result returns only one row. (like the certain one member).
You should rename your model from db to (example)db_model or other. The db will conflict with the system method.
The way to load function from model is $this->model_name->function_name for example, it should be $this->db_model->read().
You should load the model (if it is db_model) like $this->load->model('db_model') in public function __construct() { }.
In your model try out this
function read() {
$this->db->select()->from('table')->where('name', 'rabin');
$sql_stmt = $this->db->get();
return $sql_stmt->result();
}
and then to check you are getting the result - in your controller,
function show() {
$this->load->model("db");
$array= array( 'data' => $this->db->read());
$this->load->view("page", $array);
}
To view the result in your view file do print_r($data);
And then let me know what you get / result
In your view put if than else block with foreach loop in it. Smething like:
<?php if ($data != FALSE): ?>
<?php
foreach($data as $val)
{
"<p>" . echo $val['name']; . "</p>"
"<p>" . echo $val['address']; . "</p>"
}
?>
<?php else: ?>
<?php echo "There is no demanded data."; ?>
<?php endif; ?>
This is much like Benyi's answer with a little twist.
Probably you will eventually want the model to be able to look for names other than 'rabin'. So this shows how to accomplish that by passing a value to the model. Also, this model method always returns something useful to the controller.
function read($name)
{
$noRecords[] = array('name' => "No Results!", 'address' => "");
if(empty($name))
{
return $noRecords;
}
//Such a simple query does not require Query Builder which adds a
//lot of extra processing to get to the same place as this query statement
$sql = "SELECT * from table WHERE name = ?";
//This is a "bound" query that will escape the input to guard against injection attacks
$query = $this->db->query($sql, array($name));
$res = $query->result_array();
if($res->num_rows() > 0)
{
return $query->result_array();
}
else
{
// send the controller an array containing a little something to explain what happened
return $noRecords;
}
//the above if/else could also be expressed with this ternary
// return $res->num_rows() > 0 ? $query->result_array() : $noRecords;
}
The controller is now very light-weight.
function show()
{
$name = 'rabin'; //some data for the model
$array['data'] = $this->db_model->read($name);
$this->load->view('page', $array);
}
Your view is also greatly simplified
<?php foreach($data as $val): ?>
<p><?php echo $val['name']; ?>"</p>"
<p><?php echo $val['address']; ?>"</p>"
<?php endforeach; ?>

Query not assigned into the variable / Not going into the condition

I was doing this code for my project and it seems that I can't get the values of the query into $currentRow. All that saved into the variable $currentrow is 22 which is the number rows in the database. I want to have access to all the query results. Please help. Here's the code.
public function getBSIConfig(){
$conn = oci_connect("472proj","system","//localhost/XE");
$sql = oci_parse($conn,"SELECT conf_id, conf_key, conf_value FROM bsi_configure");
oci_execute($sql);
echo "0";
while($currentRow = oci_fetch_all($sql,$res)){
echo "1.5";
echo $currentRow;
if($currentRow["conf_key"]){
echo "1";
if($currentRow["conf_value"]){
$this->config[trim($currentRow["conf_key"])] = trim($currentRow["conf_value"]);
echo "2";
}else{
$this->config[trim($currentRow["conf_key"])] = false;
echo "3";
}
}
}
}
And the output is only:
0
1.5
22
The results from this function are stored in the 2nd argument, rather than returned directly. See if this works for you:
$results = array();
$numResults = oci_fetch_all($sql, $results);
foreach ($results as $result) {
if ($result["conf_key"]) {
// etc ...
}
}
Read this http://php.net/manual/en/function.oci-fetch-all.php , you might get an idea what's wrong.

How to check if results on while($row = mysql_fetch_array in PHP

Im trying to figure out how to handle this is no results are returned, how would I code that?
while($row = mysql_fetch_array($Result))
So like if there a results: print them out
else: show a link
http://ca3.php.net/manual/en/function.mysql-num-rows.php
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) { ... }
} else {
// show link
}
You can use mysql_num_rows() to tell you how many results are found. Using that with a simple if-statement, and you can determine what action to take.
if (mysql_num_rows($result) > 0) {
// do while loop
} else {
// show link
}
Others suggest using mysql_num_rows() but you should be aware that that function works only if you use a buffered query. If you query using mysql_unbuffered_query(), the number of rows in the result is not available.
I would use a simple flag variable:
$found_row = false;
while ($row = mysql_fetch_array($result)) {
$found_row = true;
. . .
}
if ($found_row == false) {
// show link
}
It may seem redundant to set $found_row to true repeatedly, but assigning a literal value to a variable ought to be an insignificant expense in any language. Certainly it is small compared to fetching and processing an SQL query result.
Use even shorter syntax without insignificant mysql_num_rows to save processor time:
if($result) {
// return db results
} else {
// no result
}
I might have figured it out:
if (!($row = mysql_fetch_array($descResult)))
{
echo "<tr><td>Add Link</td></tr>";
}
This can be done without mysql_num_rows() or an additional (flag) variable
if ( false===($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
echo 'no rows in result set';
}
else {
do {
echo $row['X'];
} while ( false===($row=mysql_fetch_array($result, MYSQL_ASSOC)) );
}
but it duplicates the actual fetch command (one in the if-statement and one in the while-clause).

Categories