hi i"ve created multiples tables in sql first time s i'm having difficulties in fetching data. so here is my code ,
<?php
// Use to fetch product data
class Product
{
public $db = null;
public function __construct(DBController $db)
{
if (!isset($db->con)) return null;
$this->db = $db;
}
// fetch product data using getData Method
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$resultArray[] = $item;
}
return $resultArray;
}
i'm only getting data from $result as i want to fetch data from $result 1-3.
i tried to run loop for all the result variables like this,
<?php
// Use to fetch product data
class Product
{
public $db = null;
public function __construct(DBController $db)
{
if (!isset($db->con)) return null;
$this->db = $db;
}
// fetch product data using getData Method
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$resultArray[] = $item;
}
return $resultArray;
// fetch product data one by one
while ($item1 = mysqli_fetch_array($result1, MYSQLI_ASSOC)){
$resultArray[] = $item1;
}
return $resultArray;
// fetch product data one by one
while ($item2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
$resultArray[] = $item2;
}
return $resultArray;
// fetch product data one by one
while ($item3 = mysqli_fetch_array($result3, MYSQLI_ASSOC)){
$resultArray[] = $item3;
}
return $resultArray;
}
but i got the error which was ::undefined variable item1-3 in line no 74::
what should i do now.
You have some mistakes in your code, i somekind of "corrected" your code for you.
return statement exits your function means code below return is not executed
you can reuse variables
use multidimensional array to store multiple tables in one array
I know its not the best way to query the database - but i hope it helps you a little
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
$resultArray[$table] = array();
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
array_push($resultArray[$table], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$liner] = array();
while ($item = mysqli_fetch_array($result1, MYSQLI_ASSOC)){
array_push($resultArray[$liner], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$eyeshadow] = array();
while ($item = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
array_push($resultArray[$eyeshadow], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$brush] = array();
while ($item = mysqli_fetch_array($result3, MYSQLI_ASSOC)){ //you can reuse $item
array_push($resultArray[$brush], $item);
}
return $resultArray;
}
Related
This question already has answers here:
return inside foreach php and laravel
(2 answers)
Closed 3 years ago.
Im fairly new to OOP way of coding and I want to fetch a record of users in my DB
This is my code below:
$con = new mysqli('localhost', 'root', '', 'goldpalace');
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
if ($num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
return $data;
}
}
}
}
$obj = new User();
$obj->connect = $con;
$user_data = $obj->get_users();
foreach ($user_data as $value) {
echo $value['name']."<br>";
}
I have a lot of records in my DB but it only returns the first row.
That's because you return the value of $data immediately after you retrieve one row. return will return that value and stop execution of that method. You need to return that value after you are done retrieving your values.
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
$data = [];
if ($num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
return $data;
}
}
FYI, you can use fetch_all() here to make this a bit simpler:
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
$data = [];
if ($num_rows > 0) {
$data = $result->fetch_all(MYSQLI_ASSOC);
}
return $data;
}
}
For you return in the first cycle in while
while ($row = $result->fetch_assoc()) {
$data[] = $row;
return $data;
}
just move the return out of while loop
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
I created a function that read data from a mysql db.
I want to put the data into a array and read that outside of the PHP function.
function showCategory($con) {
$sql = "SELECT * FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
return $kategorien;
}
}
To load the data outside from function:
$kategorien = showCategory($con);
echo $kategorien['kategorie'][0];
It doesn't work. Whats wrong?
The
return $kategorien;
will exit the loop and the function, so move this to the end of the function and not in the loop.
function showCategory($con) {
$sql = "SELECT kategorie FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
}
return $kategorien;
}
Rather than using *, it's also worth specifying the column names if you only need some of them.
Display the data using...
$kategorien = showCategory($con);
print_r( $kategorien );
or use a foreach()...
$kategorien = showCategory($con);
foreach ( $kategorien as $kat ) {
echo $kat.PHP_EOL;
}
Use this instead, because returning $kategorien will exit the loop, so it will only run once.
function showCategory($con) {
$sql = "SELECT * FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
}
return $kategorien;
}
I have a showProduct.php file from where i want to call a function showProduct() in another file. In showProduct() i want to extract all rows from database and to showProduct.php file. the issue is that when i return the array only last row is showing. I want to show all the rows.
The showProduct.php is:
<?php
require_once '../includes/DbOperations.php';
$response = array();
$result = array();
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$db = new DbOperations();
$result = $db->showProduct();
if(!empty($result))
{
$response["prod_name"] = $result["prod_name"];
$response["prod_desc"] = $result["prod_desc"];
$response["prod_image"] = $result["prod_image"];
}
else
{
$response["error"] = true;
$response["message"] = "products are not shown";
}
}
echo json_encode($response);
?>
and showProduct() function is:
public function showProduct(){
$menu = array();
$query = mysqli_query($this->con,"SELECT * FROM `products` WHERE 1");
while ($row = mysqli_fetch_array($query)) {
$menu['prod_name'] = $row['prod_name'] ;
$menu['prod_desc'] = $row['prod_desc'] ;
$menu['prod_image'] = $row['prod_image'];
}
return $menu;
}
In your function, you are just overwriting the last data each time, you need to build this data up. Create an array with the new data and use $menu[] to add this new data to the list of menus...
public function showProduct(){
$menu = array();
$query = mysqli_query($this->con,"SELECT * FROM `products` WHERE 1");
while ($row = mysqli_fetch_array($query)) {
$newMenu = []; // Clear array to ensure no details left over
$newMenu['prod_name'] = $row['prod_name'] ;
$newMenu['prod_desc'] = $row['prod_desc'] ;
$newMenu['prod_image'] = $row['prod_image'];
$menu[] = $newMenu;
}
return $menu;
}
I'm a newbie to PHP and I'm just trying the very basics of MVC. Everything is going good but I have a problem while fetching data from MySQL and populating a HTML table with it.
The problem is that my code is just returning one row of the table (there are three rows in that table).
I have tried many things and right now I'm using arrays for storing the data and passing to controller and then to the view.
Query class file having a function for getting data and name queryDB:
public function getdata(){
$connectObj=new dbConnection();
//its a connection class where mysql connection has been made
if(!$connectObj->connectDB()){
echo "Error in mysql: ".mysql_error();
return false;
}
else{
$query = "select * from tbl_cartypes";
$result = mysql_query($query) or die("Error: ".mysql_error());
$data = array();
while($row = mysql_fetch_assoc($result)){
$data[0] = $row['car_id'];
$data[1] = $row['car_name'];
$data[2] = $row['car_model'];
$data[3] = $row['car_type'];
$data[4] = $row['car_price'];
}
return $data;
}
$connectObj->closeDB();
}
The controller class where the controller of this query is name carController.php:
public function getAllData(){
$runQuery = new queryDB();
$array = array();
$array = $runQuery->getTickets($userid);
return $array;
}
And the final view where I'm just echoing my data:
include "$path/controllers/carController.php";
$ticket = new carController();
$array = array();
$array = $ticket->getdata();
for($i=0;$i<count($array);$i++){
echo $array[$i]."<br />";
}
Output of this code is without error, but the problem is that it's just fetching one row of the table whereas there are three rows.
So any one can help me with this?
It's fetching all rows, but you're saving all the data to the same place ($data[0] through $data[5]), so all but the last row is getting overwritten.
This might work better:
$data = array();
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
Using PDO and what other people have posted try using this
public function getdata(){
$connectObj=new dbConnection();
//its a connection class where mysql connection has been made
if(!$connectObj->connectDB()){
echo "Error in mysql: ".mysql_error();
return false;
}
else{
$query = 'select * from tbl_cartypes';
$result = $connectObj->query($query);
$data = array()
foreach ($result as $row){
array_push($data, $row)
}
return $data;
}
$connectObj->closeDB();
}
Your problem is that you're overwriting the values of the previous table:
while($row = mysql_fetch_assoc($result)){
$data[0] = $row['car_id'];
$data[1] = $row['car_name'];
$data[2] = $row['car_model'];
$data[3] = $row['car_type'];
$data[4] = $row['car_price'];
}
This will just re-write the last row of data over the key's in that table.
Try:
$data = array()
while($row = mysql_fetch_assoc($result)){
array_push($data, $row)
}
Your while loop is assigning just one row to array $data. in while loop instead try this
while($row = mysql_fetch_assoc($result)){
$data["car_id"][] = $row['car_id'];
$data["car_name"][] = $row['car_name'];
$data["car_model"][] = $row['car_model'];
$data["car_type"][] = $row['car_type'];
$data["car_price"][] = $row['car_price'];
}
return $data;
Now you can iterate through the array.
I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function