Basically i'm using an mySQLi wrapper i've found online and while trying to use it i've came across a problem i can't see to get past, basically, i'm performing this.
<?php
$res = $DB->Query("SELECT * FROM `table`");
while($row = $DB->Fetch()) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $functions->checkStatus($row['arowhere']); ?></td>
</tr>
<?php
}
?>
So when i'm trying to do this $functions->checkStatus($row['arowhere']); it performs a new query inside this function on my table row, it's changing the latest query which is being used for the while($row = $DB->Fetch()) {
public function Query($SQL) {
$this->SQL = $this->mysqli->real_escape_string($SQL);
$this->Result = $this->mysqli->query($SQL);
if ($this->Result == true) {
return true;
} else {
die('Problem with Query: ' . $this->SQL);
}
}
public function Fetch() {
return mysqli_fetch_assoc($this->Result);
}
Is there a solution or maybe someone point me in the correct direction so i can avoid this please.
I can't believe such a wrapper can be found online. As a matter of fact, it's completely, ultimately unusable.
Doing mysqli->real_escape_string($SQL); makes absolutely no sense. It won't protect your query from injection yet it will spoil whatever complex query. As soon as you will try to run a query with WHERE condition it will die from error.
And the following line is also wrong
die('Problem with Query: ' . $this->SQL);
as it's not showing you neither error nor file and line number.
And least this wrapper's problem is one you face - it is using internal variable to hold the result, while it should just return it.
A real mysqli wrapper is SafeMysql, which lets you to add whatever dynamical data via placeholders.
With SafeMysql your code would work:
<?php
$res = $DB->query("SELECT * FROM `table`");
while($row = $db->fetch($res)) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $functions->checkStatus($row['arowhere']); ?></td>
</tr>
<?php
}
?>
You could iterate through the rows and add them to a temporary array. You could then reference the rows via this array after other queries have been made. This could have memory implications if there are too many rows being returned by the query, so be careful.
<?php
$res = $DB->Query("SELECT * FROM `table`");
$rows = array();
while($row = $DB->Fetch()) {
array_push( $rows, $row );
}
foreach( $rows as $row ){
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $functions->checkStatus($row['arowhere']); ?></td>
</tr>
<?php
}
unset( $rows ); // destroys the temporary array, freeing the memory it consumed
?>
Related
This "do while" give me the results of a specific table.
do {
comprobe($row_DatosConsulta['strCod']);
?>
<tr class="edit">
<td class="text-center"> <?php echo $row_DatosConsulta['strCod']; ?> </td>
<td class="text-center"> <?php echo $row_DatosConsulta['strNombre'] ?> <?php echo $row_DatosConsulta['strApellido'] ?> </td>
<td class="text-center"> <?php echo $row_DatosConsulta['strMedidor'] ?> </td>
<td class="text-center"> <?php echo ObtenerDeuda($row_DatosConsulta['intDeuda']) ?></td>
<td class="text-center">
} while ($row_DatosConsulta = $Result->fetchArray(SQLITE3_ASSOC));
my problem is that when i try to use the function "comprobe" (a function that is in another page, but that page are included in the actual page) there is an error that appears, "Undefined variable" so i think that the "do while" is not sending the name to the function, and in that order, the function cant work.
I need to execute a function with all the data that generate the "do while"... for example, if there is 30 names generated by the "do while" of the table, I need to execute 30 times that function with one per one of the names.
so my question is, how could i do that?
actually I'm using SQLITE3, and my function is the next one
function actualizardeudasusu(){
$bd = new SQLite3('my_datebase.db');
$DatosConsulta = ("SELECT * FROM tblDeudas WHERE strCod='".$Codigo."' ");
$Result = $bd->query($DatosConsulta)or die("Error in query: <span
style='color:red;'>$query</span>");
$row_DatosConsulta = $Result->fetchArray(SQLITE3_ASSOC);
echo $DatosConsulta;
$CONTADOR = (" PRAGMA table_info(tblDeudas); ");
$ResultCont = $bd->query($CONTADOR)or die("Error in query: <span
style='color:red;'>$query</span>");
$conteoprevio = $ResultCont->fetchArray(SQLITE3_ASSOC);
$comprobaciondedeuda = 0;
$number = 0;
do {
$number++;
${"mes".$number} = $conteoprevio['name'];
if ($row_DatosConsulta[${"mes".$number}] != 'pagado'){
$comprobaciondedeuda = 1;
}
}
while ($conteoprevio = $ResultCont->fetchArray(SQLITE3_ASSOC));
if ($comprobaciondedeuda == 1){
$updateSQL = "UPDATE tblafiliacion SET
intDeuda='1'
WHERE strCod='".$codigo."' " ;
$Result = $bd->query($updateSQL)or die("Error in query: <span
style='color:red;'>$query</span>");
} else {
$updateSQL = "UPDATE tblafiliacion SET
intDeuda='0',
WHERE strCod='".$codigo."' " ;
$Result = $bd->query($updateSQL)or die("Error in query: <span
style='color:red;'>$query</span>");
}
}
Your problem is that do while loop is not a correct solution.
How does your do-while woork for the first time? You enter do body and try to use $row_DatosConsulta. But $row_DatosConsulta is not defined. Why? Because it will be defined later in while-check.
So, instead do-while use while:
while ($row_DatosConsulta = $Result->fetchArray(SQLITE3_ASSOC)) {
comprobe($row_DatosConsulta['strCod']);
// do other stuff here
}
I have a very simple search page running a query for one table in a DB. I have the query and fetch working. But if it doesn't find any matches to the term the user put in then I need it to say "No Rows Returned".
Here is my PHP CODE:
<?php
include('./includes/dbConnection.php');
$result = null;
if (isset($_GET['submit'])) {
// connect to database
$conn = dbConnect('localhost', 'db_admin', 'kfor.com', 'receiving');
// query the database
$stmt = $conn->stmt_init();
$searchTerm = "SELECT * FROM inventory WHERE pallet = {$_GET['pallet_id']}";
$result = $conn->query($searchTerm);
}
?>
Here is the PHP displaying the results and errors:
<?php
if ($result != null) {
if (!empty($result)) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['pallet']; ?></td>
<td><?php echo $row['serial']; ?></td>
</tr>
<?php
}
}
} else {
echo "No Results";
}
?>
Is there a better way to display "No Results Returned"? Right now it's just displaying that error upon refresh because $result does equal null.
Thanks for any help!
Remove $result = null;, it's not needed. You can check num_rows returned your query.
<?php
include('./includes/dbConnection.php');
if (isset($_GET['submit'])) {
// connect to database
$conn = dbConnect('localhost', 'db_admin', 'kfor.com', 'receiving');
$_GET['pallet_id'] = addslashes($_GET['pallet_id']);
// query the database
$stmt = $conn->stmt_init();
$searchTerm = "SELECT * FROM inventory WHERE pallet = {$_GET['pallet_id']}";
$result = $conn->query($searchTerm);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['pallet']; ?></td>
<td><?php echo $row['serial']; ?></td>
</tr>
<?php
}
} else {
echo "No Results Returned";
}
}
?>
I am creating a search function that will allow a user to search for a house in my database by postcode initially. The function can be seen below, when the function is executed and finds a true statement I get no errors however when I execute the search and I get a no fields been returned I am left with this error:
No Records Found
Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/undergradpad/search.php on line 26
I want it to display No Records Found however I don't know how I should correct the above error.
search.php:
<table width="500" border="1" cellpadding="5">
<tr>
<th width="16" scope="row">id</th>
<td width="95">bedrooms</td>
<td width="140">description</td>
<td width="104">roadname</td>
<td width="71">postcode</td>
</tr>
<?php
require("classes/class.House.inc");
$obj = new House();
$obj->search($_POST['term']);
foreach($obj->data as $val){
extract($val);
?>
<tr>
<td scope="row"><?php echo $id; ?></td>
<td><?php echo $bedrooms; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $roadname; ?></td>
<td><?php echo $postcode; ?></td>
</tr>
<?php
}
?>
</table>
classes/class.House.inc:
<?php
include("connect/class.Database.inc");
class House extends Database {
public function read(){
$query = "SELECT * FROM houses";
$result = $this->mysqli->query($query);
$num_result = $result->num_rows;
if($num_result > 0){
while($rows =$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
}
}
public function search ($term){
$query = "SELECT * FROM houses WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
$result = $this->mysqli->query($query);
$num_result = $result->num_rows;
if($num_result > 0){
while($rows =$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
} else{
echo 'No Records Found';
}
}
}
?>
in this variable ($obj->data) you just get null data.
First check if not empty and than use foreach and don't have error if yout method don't return null data
just check if (!empty($obj->data)
{
foreach code
}
$obj is a House object. It has no $data property, even if you use it. The search method sets this property, but only if records are found. If no records are found, the method echoes a value.
I would change it like this: Instead of echoing an error, make the method return false:
public function search ($term){
$query = "SELECT * FROM houses WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
$result = $this->mysqli->query($query);
$data = false;
$num_result = $result->num_rows;
while($row =$result->fetch_assoc()){
$data[]=$row;
}
return $data;
}
Now, the function return an array of false if there is no data. You can now use it like this:
$obj = new House();
if ($data = $obj->search($_POST['term']))
{
foreach($obj->data as $val){
extract($val);
}
}
The changes I made:
- No longer set data as a property, since you also return it. You can still do that, if you like, but I think it's confusing to do both.
- Return false if there's no data.
- Change the variable rows to row, since it only contains one row.
if(is_array($obj->data)){
foreach code
}
else{
no record
}
i am using codeigniter. i have a table to be displayed in a view file. so i have a model where i fire a query to get the data from table.
function my_active_requests()
{
$user_id = $this->session->userdata('user_id');
$this->db->select('id,request_date,required_by_date');
$this->db->where('requested_by',$user_id);
return $this->db->get('requests');
///also tried with
//$query = $this->db->get('requests');
///$number_of_rows = $query->num_rows;
//return $query;
//return $number_of_rows;
//but no result
}
this is the model function.
this is my controller
function my_active_req()
{
$this->bloodline_model->my_active_requests();
//also tried without this//
$query = $this->db->get('requests');
//and this//
$number_of_rows = $query->num_rows;
$this->load->view('my_active_req');
}
and this is my view
<?php foreach ($query->result() as $row) { ?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->request_date; ?></td>
<td><?php echo $row->required_by_date; } ?></td>
</tr>
</table>
but the error is undefined variable $query.
i think , i am not able to return the $query and other data from my model to controller and controller to my view.
Please provide me with the solution.
`
Change this line:
<?php
$this->load->view('my_active_req', array(
'query' => $query
));
The second parameter of the view() loader function allows you to pass variables into the view.
However, you're largely circumventing the purpose of MVC separation. You want the controller to "ask" for information from the model (not just straight from the database; otherwise, what's the point of a model?), and then "pass" it to the view. The controller knows what the view needs to function.
Model
function my_active_requests()
{
$user_id = $this->session->userdata('user_id');
$this->db->select('id,request_date,required_by_date');
$this->db->where('requested_by',$user_id);
$query = $this->db->get('requests');
if($query->num_rows) {
return $this->db->result();
}
return false;
}
Controller
function my_active_req()
{
$results = $this->bloodline_model->my_active_requests();
$this->load->view('my_active_req', array('user_data' => $results));
}
View
<?php
if($user_data) {
foreach ($user_data as $row) { ?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->request_date; ?></td>
<td><?php echo $row->required_by_date; } ?></td>
</tr>
</table>
Hello and Good Morning,
I am still learning PHP and for some reason my script will not post any data in my foreach loop. Any Idea why? The emailRow Echos out fine but I am going to remove My code is below:
<?php
include 'includes/header.php';
$accountUser = array();
$upgradeEmail = $_GET['currEmail'];
$emailQuery = "SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0";
<?php echo $emailRow['fbID']; ?>
<?php echo $emailRow['firstName']; ?>
<?php echo $emailRow['lastName']; ?>
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
?>
<table>
<?php foreach($accountUser as $emailData) { ?>
<tr><td> <?php emailData['fbID']; ?> </td><td><?php emailData['firstName']; ?></td><td><?php emailData['lastName']; ?></td></tr>
<?php } ?>
</table>
You have constructed your SQL query in $emailQuery, but never executed it. Call mysql_query(), and pass its result resource to mysql_fetch_assoc().
$emailQuery = "SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0";
$result = mysql_query($emailQuery);
if ($result)
{
while($emailRow = mysql_fetch_assoc($result, $conn))
{
$accountUser[]=$emailRow;
}
}
else // your query failed
{
// handle the failure
}
Please also be sure to protect your database from SQL injection by calling mysql_real_escape_string() on $upgradeEmail since you're receiving it from $_GET.
$upgradeEmail = mysql_real_escape_string($_GET['currEmail']);
You don't actually echo anything.
as well as not running the query.
and there are some other methods to do things, much cleaner than usual uglyPHP.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
$email = mysql_real_escape_string($_GET['currEmail']);
$data = sqlArr("SELECT * FROM users WHERE emailOne='$email' AND authLevel=0");
include 'template.php';
a template
<? include 'includes/header.php' ?>
<table>
<? foreach($data as $row) { ?>
<tr>
<td><?=$row['fbID']?></td>
<td><?=$row['firstName']?></td>
<td><?=$row['lastName']?></td>
</tr>
<? } ?>
</table>
YOU HAVE A SYNTAX ERROR. You can't open a new php tag within an existing php tag. You have to close the already open tag first.
As far as getting the query to work,
First you have to fetch data before printing it or echoing it...
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
then you may write statements..
echo $emailRow['fbID']; etc. code.
Secondly you have not fired a query, just written the query statement. Use mysql_query to fire it.
Your code would be something like this..
<?php include 'includes/header.php';
$accountUser = array();
$upgradeEmail = $_GET['currEmail'];
$emailQuery = mysql_query("SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0") or die (mysql_error());
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
echo $emailRow['fbID'];
echo $emailRow['firstName'];
echo $emailRow['lastName'];
print '<table>';
foreach($accountUser as $emailData) {
print '<tr><td>'$.emailData['fbID'].'</td><td>'.$emailData['firstName'].'</td><td>'.$emailData['lastName'].'</td></tr>';
}
print '</table';
?>
Feel free to use this code, modifying it to fit your needs.