How to fetch a table from MySQL in PHP - php

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.

Related

cannot insert query result into file

I try to insert result of query into some file.
The file is created but it contain nothing.
I check the query result and its working, i receive a result data.
here is my controller code :
$members_nik = array();
$members_nik = select_config_by('member', 'member_nik', 'WHERE 1=1');
file_put_contents("data.txt", implode(', ', $members_nik));
here is my function code :
function select_config_by($table, $obj, $where){
$query = mysql_query("SELECT $obj as result FROM $table $where");
$row = mysql_fetch_array($query);
$result = $row['result'];
return $result;}
You are returing a string from the select_config_by function but then trying to implode it as if it were an array.
Now assuming you want to return all the results and save them in your data.txt, change the function to this:
function select_config_by($table, $obj, $where)
{
$result = mysql_query("SELECT $obj as result FROM $table $where");
$temp = array();
while ($row = mysql_fetch_array($result))
{
$temp[] = $row['result'];
}
return $temp;
}

magento database sql not working

So do not have an idea why this function is not working? i am trying to select all the ids from the table but nothing is selected.
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows = ('value'=>$record, 'label'=>$record);
}
return $rows;
}
this function below works fine, I need the function above to do the same as teh function below.
public function toOptionArray()
{
return array(
array('value'=>1, 'label'=>'one'),
array('value'=>2, 'label'=>'Two'),
array('value'=>3, 'label'=>'Three'),
array('value'=>4, 'label'=>'Four')
);
}
There are a couple of issues with your code:
You're only selecting a single item (id, but later, I assume you're expecting an ID and a value).
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
record is an array from your SQL query, so you should be treating it as such. eg. $record['id']
$rows you want as an array, but you're overwriting it each time, so $rows[] = makes more sense
Something like:
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id, label FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows[] = array('value'=>$record['id'], 'label'=>$record['label']);
}
return $rows;
}
Try using the core read/write resource. Change
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
To
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');

How to select table user in yii2?

i have a trouble, when select table user in yii2 , data no show up
$sqlGetuser = "select * from user ";
$sqlquery = Yii::$app->db->createCommand($sqlGetuser)->query();
foreach($sqlquery as $row){
// echo $row;
// echo "saya";
echo $row['username'];
}
The error is in this line:
$sqlquery = Yii::$app->db->createCommand($sqlGetuser)->query();
query() returns yii\db\DataReader. To return array of rows use queryAll():
$rows = Yii::$app->db->createCommand($sqlGetuser)->queryAll();
If you want to use query(), you need to read data differently:
$command = $connection->createCommand('SELECT * FROM "user"');
$reader = $command->query();
while ($row = $reader->read()) {
$rows[] = $row;
}
// equivalent to:
foreach ($reader as $row) {
$rows[] = $row;
}
// equivalent to:
$rows = $reader->readAll();
See more in official docs.
Also quote table name as adviced since it's reserved word.

Output multiple rows in json in Zend Framework 1

I've searched and can't find an answer to my question.
I have the following code which is to loop through an array and then fetch back results for the different $id's.
The output when using echo json_encode($row); returns all results but the zend layout displays.
However when using $this->_helper->json($row,true); the layout doesn't display but only one result returns.
How can I return more than one result?
Any help would be much appreciated.
public function testAction()
{
//Get latest revision from database and loop through $id's
$id = array('308', '307', '306');
//Connect to database
foreach($id as $lId) {
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select('')
->from('LinktagRevisions')
->where('linktagId = ?', $lId)
->order('updated DESC')
->limit(1);
$stmt = $select->query();
while ($row = $stmt->fetch()) {
$this->_helper->json($row,true);
//Encode as json and echo result
// echo json_encode($row);
}
}
}
I think you can try this:
$result = array();
foreach($id as $lId) {
....
$stmt = $select->query();
$result[$lId] = $stmt->fetchAll();
}
$this->_helper->json($result,true);

Insert sql query result to a new query

So the task is:
Do a query like Select * from table.
Take some cell value
Insert this value to a new query.
What do I have so far:
$Conn = odbc_connect("...");
$Result = odbc_exec("Select ...");
while($r = odbc_fetch_array($Result))
// showing result in a table
Here it looks like I should use the r array and insert data like
$var = r['some_field'];
$query = 'Select * from table where some_field = {$var}";
But how can I fill this array with values and how to make it available out of while loop?
Here I'm using odbc, but it doesn't matter, I need the algorithm. Thanks.
The whole code looks like:
<?php
$data = array();
$state = 'false';
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
$data = array();
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
$state = 'true';
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//I need to use $data HERE. Doesn't work
// $state = 'false' here...
}
?>
Define array outside while loop
$data = array();//defining
while($r = odbc_fetch_array($Result))
use array_push() inside while loop
array_push($data, $r['some_field']);
then try to print array of complete data outside loop
print_r($data);
Updates
Place $data = array(); at the top of first IF statement. Try this code:
$data = array();//at top
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//print_r($data) works here also
}
try something like this to store data in array
$allrows = array();
while($r = odbc_fetch_array( $result )){
$allrows[] = $r;
}
use foreach loop to print or use as per your choice
foreach($allrows as $singlerow) {
//use it as you want, for insert/update or print all key value like this
foreach($singlerow as $key => $value) {
//echo $key . '=='. $value;
}
}
You can try this as i understand your query hope this is your answer
$arr ='';
while($row = odbc_fetch_array($Result)) {
$arr .= '\''.$row['some_field'].'\',';
}
$arr = trim($arr, ",");
$query = "SELECT * from table where some_field IN ($arr)";
Your all task can be completed in single query
INSERT INTO table2 (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM table1

Categories