How to print multiple row with several columns in a template? - php

I have a problem to find a way to get the MySQL-Result returned into an array which contains the data from the statement for every row and column.
controller.class.php:
class Controller {
private $template;
private $view;
private $data;
public function __construct() {
$this->view = new View();
$this->data = new Model();
}
public function display() {
$this->view->setTemplate();
$this->view->setContent("title", "Songs");
$this->view->setContent("content", $this->data->getAllDataFromSongs());
$this->view->setContent("footer", "&copy My name is Jeff\n");
return $this->view->parseTemplate();
}
}
model.class.php:
class Model {
public $db_connection = null;
public function __construct() {
$this->openDatabaseConnection();
}
private function openDatabaseConnection() {
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($this->db_connection->connect_error) {
die('Connect Error (' . $this->db_connection->connect_errno . ') '
. $this->db_connection->connect_error);
}
}
public function getAllDataFromSongs() {
$query = "SELECT * FROM songs";
$row_content = array();
if ($result = $this->db_connection->query($query)){
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
array_push($row_content, $row['id']);
array_push($row_content, $row['artist']);
array_push($row_content, $row['song']);
array_push($row_content, $row['year']);
}
$result->free();
return $row_content;
}
else
echo 'No results';
}
}
view.class.php:
class View {
private $path = 'templates';
private $template;
private $content = array();
public function setContent($key, $value){
$this->content[$key] = $value;
}
public function setTemplate($template = 'default') {
$this->template = $this->path . DIRECTORY_SEPARATOR . $template . '.tpl.php';
}
public function parseTemplate() {
if (file_exists($this->template)) {
ob_start();
require_once('templates/header.tpl.php');
include_once $this->template;
require_once('templates/footer.tpl.php');
$output = ob_get_contents();
ob_end_clean();
return $output;
}
else{
return "Can't find ".$this->template." Template";
}
}
}
default.tpl.php:
<table>
<tr>
<th>ID</th>
<th>artist</th>
<th>song</th>
<th>year</th>
</tr>
<tr>
<?php
foreach ($this->content['content'] as $con){
echo '<td>'. $con . '</td>';
}
?>
</tr>
</table>
<br>
<?php echo $this->content['footer']; ?>
It's not the entire Code, but it should show you what I'm trying.
The problem which I have now, is that the result from getAllDataFromSongs() is an Array with all Datas in behind each other. I can't separate them in a table.
This is the output:
Array (
[0] => 1 [1] => Artist 1 [2] => Song 1 [3] => Year 1
[4] => 2 [5] => Artist 2 [6] => Song 2 [7] => Year 2
[8] => 3 [9] => Artist 3 [10] => Song 3 [11] => Year 3
[12] => 4 [13] => Artist 4 [14] => Song 4 [15] => Year 4
[16] => 5 [17] => Artist 5[18] => Song 5 [19] => Year 5
)
ID artist song year
1 Artist 1Song 1Year 12Artist 2Song 2Year 2 3Artist 3Song 3Year 3...
I hope you can relate what I'm trying to explain..

while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
array_push($row_content, $row['id']);
array_push($row_content, $row['artist']);
array_push($row_content, $row['song']);
array_push($row_content, $row['year']);
}
Your problem here is that you are creating a new array element for each column, so in the end you will have them all one after the other, one the same level.
Either create a temporary array first, and then assign that (so that you get rows of columns),
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$temp = [];
array_push($temp, $row['id']);
array_push($temp, $row['artist']);
array_push($temp, $row['song']);
array_push($temp, $row['year']);
array_push($row_content, $temp);
}
Or, assign just the full row array directly:
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
array_push($row_content, $row);
// $row_content[] = $row; // same thing
}
If you get additional columns from your SELECT statement that you don’t want in here, then you should name the columns directly in the SELECT statement, instead of selecting *.)
Additionally, mysqli_result::fetch_all also exists. That function puts all rows in the result set in an array in one go - so you could do away with the while loop completely.

Related

PHP Count Similiar Values in multiple arrays

I have values in database like these :
Row 1 : ["2","3"]
Row 2 : ["1","3"]
Row 3 : ["2","3","4"]
In frontend i selected all rows, now i want to show count of similar values.
For eg : Desired o/p from above code : Count for 1 = 1 , 2 = 2 , 3 = 3 , 4 = 1
When i json_decode above values and using print_r i got like these :
Array ( [0] => 2 [1] => 3 )
Array ( [0] => 1 [1] => 3 )
Array ( [0] => 2 [1] => 3 [2] => 4 )
Note : List of rows can be increased, how can i find similar values.
I tried array_intersect as shown here , but didn't work.
Eg: image here
Please Note Data in image, is different from above data
Code to get above data :
$conn = new mysqli("localhost", "root", "", "ams");
$query="SELECT * FROM attendance WHERE subject = '$subj'";
$result = $conn->query($query);
<table class="table table-responsive">
<tr>
<th>Sr. No</th>
<th>Col 1 </th>
<th>Col 2</th>
</tr>
<form method="post">
<?php
$i=1;
if (mysqli_num_rows($result) > 0) {
while ($row=mysqli_fetch_assoc($result)) {
$data = $row['att'];
$data = json_decode($data);
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row['date1'] . "</td>";
echo "<td>" . print_r($data) . "</td>";
echo "</tr>";
$i++;
}
}
?>
</form>
</table>
So, I made this class for you. It will create the connection when you initalize it.
class RowData {
private $connection;
private $returnContent = array();
private $stmt = null;
function __construct() {
$connection = new PDO("mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DB, MYSQL_USERNAME, MYSQL_PASSWORD);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection = $connection;
}
public function get($subj) {
$this->getContentFromDB($subj);
$this->parseContent();
return $this->returnContent;
}
private function getContentFromDB($subj) {
$stmt = $this->connection->prepare("SELECT * FROM attendance WHERE subject = '{$subj}'");
$stmt->execute();
$this->stmt = $stmt;
}
private function parseContent() {
$content = $stmt->fetchAll(PDO::FETCH_OBJ);
if(count($content) < 1) {
throw new Exception('Unable to find any attendies');
}
foreach($content as $values) {
$row = $this->getJsonArray($values->att);
$this->findValues($row);
}
}
private function getJsonArray($content) {
return json_decode($content);
}
private function findValues(array $row) {
foreach($row as $key => $value) {
if(isset($this->returnContent[$value])) {
$this->returnContent[$value] = $this->returnContent[$value] + 1;
} else {
$this->returnContent[$value] = 1;
}
}
return;
}
}
So, let me explain it. The constructor will be the function that is initialized when you write $x = new RowData();. It creates the connection the the MySQL database. All you have to do is change the MYSQL_HOST, MYSQL_DB, MYSQL_USERNAME, MYSQL_PASSWORD values to the appropriate ones. The only function that is available for you to use publicly would be the get() function. The get() function calls 2 separate functions and accepts one value as a parameter. The one value is what you called $subj. One of the functions in the get() function just gets the content from the MySql Table using the query you provided. The second function parseContent() gets an obj from PDO and loops through it. lastly, there is the findValues() function that accepts $row as a parameter. This function will see if the number is already in the data set. If it is, then it is basically a counter. Otherwise, it makes a new key and sets the value to 1.
The values returned from the get() function would be something like this:
array(2=>2, 1=>1, 3=>3, 4=>1)
To use this class, you would write something like this:
$rowData = new RowData();
try {
$content = $rowData->get();
} catch (Exception $e) {
// No results were found
}
Hope this helps! If you need help implementing this, let me know and i'll be more than happy to help you out!

Fatal error: Cannot use object of type News as array tried using foreach

Am using following code to get values for SQL from specific id
include 'classes/connection.class.php';
include 'classes/news.class.php';
$connection = new Connection('localhost', '1video', 'sanoj', '123456');
$news = new News($connection->getDb());
$id=$_GET['name'];
try {
print_r($news->get($id));
and it works
RESULT
Array ( [id] => 103 [title] => bkjbjkuk [location] => 1video.com_81e81be69867c77aea1b9f630c4cf482.mp4 [thumb] => 1video.com_81e81be69867c77aea1b9f630c4cf482.jpg [views] => 1 [likes] => 1 [uploader] => lawrence [added_on] => 19-Feb-16 [tags] => hhuhuhuo [duration] => [comments] => [shortstory] => hihouihohoh )
but i need to echo result in specific location but doesn't works
Method 1
include 'classes/connection.class.php';
include 'classes/news.class.php';
$connection = new Connection('localhost', '1video', 'sanoj', '123456');
$news = new News($connection->getDb());
$id = $_GET['name'];
try {
print_r($news->get($id));
foreach ($news->result() as $row) {
$news= $row->title;
?>
<h3><?php echo $vidid ?></h3>
Fatal error: Call to undefined method News::result()
can someone guide me how do i echo array() in various location
class news
class News {
private $db;
private $newsByPage = 5;
public function __construct(PDO $db)
{
$this->db = $db;
}
public function get($id)
{
$q = $this->db->prepare("SELECT * FROM videos WHERE id = :id");
$q->bindValue(":id", $id, PDO::PARAM_INT);
if(!$q->execute())
{
$errors = $q->errorInfo();
throw new Exception("Error while getting a news (".$errors[2].").");
}
else
{
if($res = $q->fetch(PDO::FETCH_ASSOC)){
return $res;
}else{
throw new Exception("No match for id(".$id.").");
}}
$q->closeCursor();
}
}
It should be like:
try {
$myNews = $news->get($_GET['name']);
echo $myNews['title'];
} // -------

push array data in every index of an array using codeigniter php

I have two tables sport_tbl, match_tbl. In sport_tbl, i defined sport_name such as cricket. In match_tbl, I have match_name,match_date,sport_id.
I want to show match_date of every sport_name (ex. i am showing match_date list for cricket sport and i want to show every date has match_name list).
I want to show one distinct match_date.
Image
my controller code:-
$url = 'cricket' // for example first sport_name
$data['getSportMatch'] = $this->user_model->getSportMatch($url);
my model code:-
public function getSportMatch($sport)
{
$query = $this->db->get_where('match_tbl',array('sport_name' => $sport));
if($query->num_rows > 0)
{
foreach($query->result() as $item){
$data[] = $item;
}
return $data;
}
}
my code in view:-
<div><?php foreach($getSport as $item): ?><h4><?= $item->sport_name; ?></h4><div><?= foreach($getSportMatch as $item): ?>
match_date)) ?>here i want to show list match_name of every match_date
My table structure images
1) sport_tbl
2) match_tbl
3) another match_tbl
you can solve this in model easily. if i did not understand wrong . you need 2 function in model.
1. will get sport names
2. will get matches of given sport name
//model functions
function get_sports(){
$data = array();
$sports = $this->db->select('sport_name')->from('sport_tbl')->get()->result();
if($sports)
{
foreach($sports as $sport){
$data[$sport->sport_name] = $this->get_matches($sport->sport_name);
}
return $data;
}
}
function get_matches($sport_name){
$matches = $this->db->select('*')->from('match_tbl')->where('sport_name',$sport_name)->get()->result();
return $matches;
}
so in view data will be something like this
$data => array(
'cricket'=> array(0 => array(
'match_id' => 11,
'sport_id' = 2 .....
)))
Try this coding ...
public function getSportMatch($sport)
{
$query = $this->db->query("SELECT * FROM sport_tbl as st INNER JOIN match_tbl as mt ON st.sport_id = mt.sport_id WHERE st.sport_name ='".$sport."'");
if($query->num_rows > 0)
{
$query_result = $query->result_array();
$final_result = array();
foreach($query_result as $result ) {
$date = $result['match_date'];
$final_result[$date][] = $result;
}
return $final_result;
}
}
View Coding :-
if(isset($final_result)) {
foreach($final_result as $result) {
echo $result['match_date']; // First display match date
if(isset($result['match_date'])) {
foreach($result['match_date'] as $match) {
echo $match['match_name']; // Second listout the match name
}
}
}
}

insert array element into database

I have this function : it's work correctly,
function ms_get_did_detail($id) {
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2)) {
while($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC)) {
return $row2;
}
return 0;
}
return 0;
}
I want insert every element (every Dest & Priority) into MYSQL
if($info=ms_get_did_detail($value)) {
print_r($info);
$destination = $info['Dest'];
$priority = $info['Priority'];
my_did_destination ($priority , $dest , $active , $did_voip , $cc_id);
}
It returns array like this :
[0]=> Array (
[Dest] => 100
[Priority] => 1
)
[1]=> Array (
[Dest] => 200
[Priority] => 3
)
[2] => (
)
also , I have this function to insert value in database :
function my_did_destination($priority="",$destination="") {
global $link_voip;
$sql="INSERT INTO cc_did_destination (destination,priority)
VALUES ('$destination','$priority')";
$retval = mysql_query( $sql , $link_voip);
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
}
but It's insert empty value within
You are inserting all rows with an ID of 0, so, if a row with id=0 already exists, it will fail and will not be inserted.
Maybe the easiest solution would be to make yout ID column autoincrement with an SQL statement like:
ALTER TABLE cc_did_destination
MODIFY COLUMN id INT auto_increment;
And then change your INSERT statement for:
$sql="INSERT INTO cc_did_destination (destination,priority)
VALUES ('$destination','$priority')";
Your $info is array of rows, it has numeric keys, not 'Dest'.
You should add index, like $dest = $info[0]['Dest'].
if($info=ms_get_did_detail($value))
{
print_r($info);
$dest = $info[0]['Dest'];
$priority = $info[0]['Priority'];
my_did_destination ($priority , $dest , $active , $did_voip , $cc_id);
}
Or you can iterate through $info with a loop:
if($info=ms_get_did_detail($value))
{
foreach($info as $row) {
$dest = $row['Dest'];
$priority = $row['Priority'];
my_did_destination ($priority , $dest);
}
}
also, remove id from your insert statement
your array is:
[0]=> Array (
[Dest] => 100
[Priority] => 1
)
[1]=> Array (
[Dest] => 200
[Priority] => 3
)
[2] => (
)
so it is a multidimensional array. if you need to insert all those entries, you shouldn't run multiple queries for the same thing. just use mysql batch insert syntax. (e.g. INSERT INTO tbl (col1,col2,col3) VALUES(a,b,c),(d,e,f),(g,h,i))
build the query string for insert.
foreach($a as $i => $v)
{
$b[] = '("'.$v['Dest'].'","'.$v['Priority'].'")';
}
$c = implode(',', $b);
$sql = "INSERT INTO cc_did_destination (destination,priority)
VALUES ".$c;
then run the query
N.B.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
There are a couple of issues here.
Firstly your first function returns an array of arrays. Ie, it returns an array with subscript 0 for the first row (it only ever returns one rows details), which is an array containing that rows details.
You assign this to the $info variable, so it contains:-
[0]=> Array (
[Dest] => 100
[Priority] => 1
)
You then assign $info['Dest'] to $destination and $info['Priority'] to $priority. However neither of these exist. You would need $info[0]['Dest'] and $info[0]['Priority'].
2nd issue is that you are trying to assign a specific value to the auto increment id field. Just leave it out of the insert, or give it a value of null.
Quick rewrite and I would suggest you need something like this:-
<?php
if($info=ms_get_did_detail($value))
{
print_r($info);
foreach($info AS $info_row)
{
$destination = $info_row['Dest'];
$priority = $info_row['Priority'];
my_did_destination ($priority , $dest , $active , $did_voip , $cc_id);
}
}
function ms_get_did_detail($id)
{
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2))
{
if ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
while ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
}
return $row2;
}
else
{
return 0;
}
}
return 0;
}
function my_did_destination($priority="",$destination="")
{
global $link_voip;
$priority = mysql_real_escape_string($priority);
$destination = mysql_real_escape_string($destination);
$sql="INSERT INTO cc_did_destination (id,destination,priority) VALUES (NULL,'$destination','$priority')";
$retval = mysql_query( $sql , $link_voip);
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
}
EDIT
If you want to avoid multiple inserts unnecessarily then it might be easier to use an object. This way you can do the inserts easily when there are enough batched up (I normally do 255 at a time).
Something like this, although you probably should use mysqli_*
<?php
if($info=ms_get_did_detail($value))
{
print_r($info);
$insert_object = new insert_details($link_voip);
foreach($info AS $info_row)
{
$insert_object->set_row($info_row['Priority'], $info_row['Dest']);
}
unset($insert_object);
}
function ms_get_did_detail($id)
{
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2))
{
if ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
while ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
}
return $row2;
}
else
{
return 0;
}
}
return 0;
}
class insert_details()
{
private $db;
private $insert_row = array();
public function __CONSTRUCT($db)
{
$this->db = $db;
}
public function __DESTRUCT()
{
$this->do_insert();
}
public function set_row($priority="",$destination="")
{
$priority = mysql_real_escape_string($priority, $this->db);
$destination = mysql_real_escape_string($destination, $this->db);
$this->insert_row[] = "(NULL,'$destination','$priority')";
if (count($this->insert_row) > 255)
{
$this->do_insert();
}
}
private function do_insert()
{
$sql="INSERT INTO cc_did_destination (id,destination,priority) VALUES ".implode(',', $this->insert_row);
$retval = mysql_query($sql, $this->db);
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
$this->insert_row = array();
}
}
Quick rough mysqli_* equivalent, assuming that $link_voip is a mysqli connection. Note that prepared statements with bound parameters are an option (and it makes it harder to forget to escape variables), but it can become a bit messy when you are doing multiple inserts like this.
<?php
if($info=ms_get_did_detail($value))
{
print_r($info);
$insert_object = new insert_details($link_voip);
foreach($info AS $info_row)
{
$insert_object->set_row($info_row['Priority'], $info_row['Dest']);
}
unset($insert_object);
}
function ms_get_did_detail($id)
{
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2))
{
if ($row2[]=mssql_fetch_array($res2, MSSQL_ASSOC))
{
while ($row2[]=mssql_fetch_array($res2, MSSQL_ASSOC))
{
}
return $row2;
}
else
{
return 0;
}
}
return 0;
}
class insert_details()
{
private $db;
private $insert_row = array();
public function __CONSTRUCT($db)
{
$this->db = $db;
}
public function __DESTRUCT()
{
$this->do_insert();
}
public function set_row($priority="",$destination="")
{
$priority = mysqli_real_escape_string($this->db, $priority);
$destination = mysqli_real_escape_string($this->db, $destination);
$this->insert_row[] = "(NULL,'$destination','$priority')";
if (count($this->insert_row) > 255)
{
$this->do_insert();
}
}
private function do_insert()
{
$sql="INSERT INTO cc_did_destination (id,destination,priority) VALUES ".implode(',', $this->insert_row);
$retval = mysqli_query($this->db, $sql);
if(! $retval )
{
die('Could not enter data: ' . mysqli_sqlstate($this->db));
}
$this->insert_row = array();
}
}

get data from array in cakephp

I'm trying to get the data from array in my controller php on Cakephp.
I have this function:
public function updateUserStatus() {
if(isset($this->params['url']["pcs"])) {
$uus = array( "pcs" =>$this->params['url']["pcs"] );
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
And I want to get the data from status_id who have this response:
Array (
[0] => Array
(
[status_id] => 2
)
[1] => Array
(
[rem_time] => 66
)
)
How can I do it?
My question is how can i get the data for status_id ?
public function updateUserStatus() {
if (isset($this->params['url']["pcs"])) {
$uus = array("pcs" =>$this->params['url']["pcs"]);
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$currentStatus = 0;
if (is_array($trans) && isset($trans['status_id'])) {
$currentStatus = $trans['status_id'];
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
public function updateUserStatus($uus){
if(isset($uus["pcs"])) {
$sql = "SELECT status_id as status_id , rem_time as rem_time FROM phones WHERE pcs = '".$uus["pcs"]."' LIMIT 1";
$query = $this->query($sql);
return $query[0]['phones'];
} else {
return "failed";
}
}
Notice, we are returning $query[0]['phones'].
Let me know if it works.
The code could also use some refactoring.
For example, why is the function called updateUserStatus if it is only returning the result of a query? It should also always return an array, for consistency.

Categories