Yii2: How to show SQL results? - sql

I want to show the result of this SQL query execution in a view:
$results = Yii::$app->getDb()->createCommand('SELECT * FROM colors')->queryAll();
$people = print_r($results);
<?= $people ?>
But it always shows: 1
The results should be a table with 3 columns and 10 rows. So I don't know why it shows 1. I tried with different tables but always shows the same.

depend of your need you
QueryALL return All rows of the query result.
Each array element is an array representing a row of data
so you could simple iterate over you $result
foreach($result as $key => $row){
echo $row['column1'] . '<br />' ;
echo $row['column2'] . '<br />' ;
....
}
otherwise you can use the queru for build a sqlDataProvider and the manage the models show with widget (eg: gridView)

wrong usage of print_r. see this link. did you mean:
$people = print_r($results, true);
or just use var_dump to avoid confusion.
$results already contains your rows.

This way you'll see this array $results.
$results = Yii::$app->getDb()->createCommand('SELECT * FROM colors')->queryAll();
echo "<pre>";
print_r($results);
exit;

Related

Pagination with PDO prepare statement

I am using David Carr's pagination class successfully for a whole-table call (i.e. where I'm calling all the rows in the table without filtering). After including my config and the class, I accomplish it this way:
$pages = new Paginator('3','p');
$stmt = $dbh->query('SELECT count(id) FROM sermons');
$row = $stmt->fetch(PDO::FETCH_NUM);
$total = $row[0];
//pass number of records to
$pages->set_total($total);
$results = $dbh->query('SELECT * FROM sermons ORDER BY date_preached DESC '.$pages->get_limit()); ?>
<div class="paging"><p><?php echo $total; ?> sermons found</p> <?php echo $pages->page_links();?></div>
<?php
foreach($results as $row)
Etc.
That works great, but now I'm trying to implement it for the result of user filtering via forms, and because I can't use an unnamed placeholder in the query, I'm trying to do it with a prepare (which I'm guessing is more secure anyway):
$pages = new Paginator('2','p');
$series = isset($_POST['series']) ? $_POST['series'] : false;
try {
$stmt = $dbh->prepare("SELECT count(id) FROM sermons WHERE series = ?");
$stmt->execute(array($series));
$row = $stmt->fetch(PDO::FETCH_NUM);
$total = $row[0];
//pass number of records to
$pages->set_total($total);
$results = $dbh->prepare("SELECT * FROM sermons WHERE series = ? ".$pages->get_limit());
$results->bindParam(1, $series, PDO::PARAM_STR);
$results->execute(array($series));
// the call
echo $total; ?> sermons found</p> <?php echo $pages->page_links();
When I first get to the results page from the form, it looks like everything is working properly. The call correctly identifies the number of sermons found for the search result, and displays the first two (or however many I set in the $pages statement). But when I click to another page result, no sermons display, the count is gone, and my !isset(found_rows) echo returns a zero as well.
I was originally thinking the issue was that at first I was trying to do this without binding. That is questionable, since without the pagination I can display the page without binding. In any case, I've been trying that with both bindValue and bindParam, but with no luck.
Am I mishandling something in the prepare statement? Or what?
Note: I have the results page displaying fine without the pagination with this:
$series = isset($_POST['series']) ? $_POST['series'] : false;
try {
$results = $dbh->prepare("SELECT * FROM sermons WHERE series = ?");
$results->execute(array($series));
// Etc.

SQL Results Pagination

I'm having a bit of trouble paginating my sql query results using PHP. I have tried a few different solutions but have had no success so far. Would someone be able to help me please? Below is my current code I use to display all results however I'd like them splitting into pages of 50.
<?
//query
$data = mysql_query("SELECT * FROM names");
//counts_result
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "ERROR";
}
else {
echo "<div class='search_result_output'>
SEARCH SUCCESS
</div><hr>";
}
?>
<?
//display results
while($result = mysql_fetch_array( $data ))
{
echo "<div class='panel panel-default'>";
echo "<div class='panel-heading'>";
echo "<h4 class='panel-title'>";
echo $result['name'];
echo "</h4>";
echo "</div>";
echo "<div class='game_actions' style='float:right; margin-top:-40px; margin-right:10px;'>";
echo "<a data-toggle='collapse' class='btn btn-custom' data-parent='#accordion' href='#".$result['id']."' title='More Info on ".$result['name']."'><i class='fa fa-plus'></i></a>";
echo "</div>";
echo "<div id='".$result['id']."' class='panel-collapse collapse'>";
echo "<div class='panel-body'>";
echo $result['name'];;
echo "</div>";
echo "</div>";
echo "</div>";
}
}
?>
You have this:
$data = mysql_query("SELECT * FROM names");
instead use this:
$page = (isset($_GET["page"])) ? $_GET["page"] : "0";
$data = mysql_query("SELECT * FROM names limit ".$page.", 50");
Display your links accordingly; add the page value to them. Your paging depends on the get parameter named "page".
EDIT:
If you want to display a link pointing to the 5th page, for instance, then:
echo '5';
4 * 50 = page index * page size. Page index is 4, as on the first page you have no offset. It is difficult to add any more help, since I do not know what kind of paging you need. However, this edit should help you to start solving your problem.
try something like this query and then just just change parameter i.e (3 and 8)
Select * from
(select Id,Name ,ROW_NUMBER() over (order by Id) as RowNum from Person.dbo.pers
) tbl
Where tbl.RowNum between 3 and 8
it gets 3 to 8 rows

fetch image and text from database using joomla 2.5

i have one one issue in fetch image and text from database by module what to do for this issue and i add my table name and field name #__home_service_item this is my table name in that table two field one is image and image_name than i have one error for that question i display my error
Warning: Invalid argument supplied for foreach() in C:\wamp\www\Joomla_2.5.8-Stable-Full_Package\modules\mod_home\tmpl\default.php on line 40
please give me any clue for that problem i also add my code
<?php
defined('_JEXEC') or die('Restricted access');
$items = $params->get('items', 1);
$db =& JFactory::getDBO();
$query = "SELECT id
FROM #__home_service_item
WHERE published = '1'
ORDER BY id DESC";
$db->setQuery( $query, 0 , $items );
$rows = $db->loadObjectList();
foreach($rows as $row)
{
echo 'ID: '.$row->id.' </br>';
}
?>
please give one clue
do print_r($rows) and see if any records are returning from the database. I think that you have a problem with your query. If there are no results returning try enclosing your foreach statement with in a try catch or ignore warnings.
Also try to set $db->setQuery($query); instead of $db->setQuery( $query, 0 , $items );
If you just need one row result use $db->loadResult();

How to get multiple POST data?

I am trying to get the $_POST data from some inputs fields, but the thing is I am getting the number of fields from my database:
$query2 = $DB->prepare("SELECT * FROM params WHERE modulid = $parameterid");
$query2->execute();
<td>Parameter unit:</td>
<?php while (($row2 = $query2->fetch()) != false)
{
$unit = $row2->name;
?><td><input type="text" name="<?php echo $row2->id; ?>" value="<?php echo $unit; ?>" class="textbox"></td><?php
}
?>
What is the code to get post data from all of them so I can update the database if the user wants to type new data in the input?
You can get all values submitted by a form by iterating through the following global variable:
$_POST
By using a foreach loop, you can then check which values were filled and generate an UPDATE SQL statement with them.
Example to get all non-empty values:
$changed = array();
foreach($_POST as $key => $value) {
if(!empty($value)) {
$changed[$key] = $value;
}
}
Then create the query using the $changed array.
Why don't you do something like that
$temp=$row2->id;
mysql_query("insert into params (modulid) values ('$temp')");

Issue in making appear all database table field names

I have this code which i use in order to make appear all the names of a table of a database.
It used to work... but suddenly it won't make appear anything..
Could you please take a look?
I'm working with SQL.
$section = "SELECT * FROM forma";
$res = odbc_exec($connection, $section) or die(odbc_error());
$firstrow = false;
while ($row = odbc_fetch_array($res)){
if (!$firstrow) {
foreach ($row as $column => $value) {
echo "<label> " . $column . "</label>";
echo "<input type='checkbox' name='data[]' value='" . $column . "' /><br/><br/>";
}
$firstrow = true;
}
}
Thanks
This is a fairly nasty way of retrieving the column names for a table. What it is doing is reading all the data in the table, ignoring the result set and only using it for the column names. What is happening however is that the table is empty and so nothing is being returned at all.
You need to amend the query to look at the meta data rather than the table itself. You will need to rework it. This SQL will retrieve the column names for that table for you...
Select Columns.Name
From Sys.Columns
Where Object_Name(Columns.Object_id) = 'forma'
Order By Columns.Column_Id;
After that you will need to rejig your code to take advantage of it.