PHP Query:
<?php
$query = $db->prepare('SELECT * FROM Locations WHERE user_id = :id LIMIT 0, 5');
$query->bindParam(":id",$id);
$result = $query->execute();
$rows = $query->fetch();
foreach ($rows as $row) {
echo $row["timestamp"]; "<br />";
}
?>
The two rows that should be printed (timestamp):
What actually prints:
1188((22
The error within the console:
PHP Warning: Illegal string offset 'timestamp' in /Sites/pages/user_account.php on line 73 - Line 73 being the echo $row... inside the forloop.
Any help would be greatly appreciated.
You are using fetch, which retrieves a single row, instead of fetchAll:
$rows = $query->fetchAll();
You have two rows (user_id = 8)
$rows = $query->fetchAll();
For all rows
foreach ($rows as $row) {
echo $row . "<br />";
}
For 1 row , all column
while ($row = $rows) {
foreach ($row as $column) {
echo $column . "<br />";
}
}
Related
I want to create a database query in a view helper, this works with the following code:
$uid = 11;
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_test_domain_model_author');
$query = $queryBuilder
->select('*')
->addSelectLiteral(
$queryBuilder->expr()->count('tx_test_domain_model_author.author', 'counter')
)
->from('tx_test_domain_model_author')
->join(
'tx_test_domain_model_author',
'tx_test_publication_author_mm',
'tx_test_publication_author_mm',
$queryBuilder->expr()->eq(
'tx_test_domain_model_author.uid',
$queryBuilder->quoteIdentifier('tx_test_publication_author_mm.uid_foreign')
)
)
->where(
$queryBuilder->expr()->eq(
'tx_test_publication_author_mm.uid_local',
$queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
)
)
->orderBy('tx_test_domain_model_author.uid', 'ASC');
$result = $query->execute();
$res = [];
while ($row = $result->fetch()) {
$res[] = $row;
}
print_r($res);
However, I only get one record, although the counter tells me it would be 3.
What am I doing wrong?
If the counter says its three items, then try change this:
$result = $query->execute();
$res = [];
while ($row = $result->fetch()) {
$res[] = $row;
}
into this:
$result = $query->execute()->fetchAll();
That fetches all rows into an array that you walk throug with:
foreach($result as $row){
...
}
It seems the QueryBuilder works differently, this gives me one result namely the first entry in the table:
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_test_publication_author_mm');
$query = $queryBuilder
->select('*')
->from('tx_test_publication_author_mm');
$result = $query->execute()->fetchAll();
foreach($result as $row){
echo $row['field'];;
}
This gives me all results:
$db = mysqli_connect($dbHost, $dbUser, $dbPassword, $dbName) or die (mysql_error ());
$sql = "SELECT * FROM tx_test_publication_author_mm";
foreach ($db->query($sql) as $row) {
echo $row['field'];
}
I use an html string in php to display sql query results in a single column:
How can I use multiple columns to lay it out like this:
while($row = mysqli_fetch_array($q)){
$id = $row['id'];
$title = $row['title'];
$desc = $row['description'];
$link = $row['link'];
$output .= '<a href="' . $link . '">
<h3>' . $title . '</h3>
<p>' . $desc . '</p>
</a>';
}
Credit to hungrykoala for help on this one
$i = 0 ;
$resultsPerRow = 2 ;
$output = '<tr>';
while($row = mysqli_fetch_array($q)){
$i++;
$id = $row['id'];
$title = $row['title'];
$desc = $row['description'];
$link = $row['link'];
$output .= '<td>' .$title. '<br>' .$desc. '</td>';
if ($i % $resultsPerRow == 0) {
$output .= '</tr><td><br></td><tr>';
}
}
echo($output);
Then output to a table tag
I have a good result using PDO query retrieve all data from database.
But, this only display the result with LIMIT like 10.
My questions now is how to paste this result for paginate?
I want to set result for 10 perpage and have prev 1 2 3 4 next for all data.
below script is good and fast result for me.
<?php
//load database connection
$host = "localhost";
$user = "root";
$password = "";
$database_name = "";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from table where colum1 LIKE '%$search%' OR colum2 LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Title Books</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Author</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Price</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['name'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['description'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo "$".$results['thumb'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
I would suggest that you create a class for pagination then include the class.
pagination.php
<?php
class paginate
{
private $pdo;
function __construct($pdo)
{
$this->db = $pdo;
}
public function dataview($query,$Search)
{
$stmt = $this->db->prepare($query);
$stmt->execute(arary($Search,$Search));
$results = $stmt->fetchall();
if (count($results) > 0) {?>
Search found : <br/>
<table style="font-family:arial;color:#333333;">";
<tr><td style="border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;">Title Books</td><td style="border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;">Author</td><td style="border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Price</td></tr>
<?php
foreach ($results as $row):
?>
<tr><td style="border-style:solid;border-width:1px;border-color:#98bf21;">
<?php echo $row['name'];?></td>
<td style="border-style:solid;border-width:1px;border-color:#98bf21;">;
<?php echo $row['description'];?>
</td>
<td style="border-style:solid;border-width:1px;border-color:#98bf21;">
<?php echo $row['thumb'];?>
</td></tr>
<?php
endforeach;
echo "</table>";
} else {
echo "<p> Nothing found </p>";
}
}
public function paging($query, $records_per_page)
{
$starting_position = 0;
if (isset($_GET['page_no'])) {
$starting_position = ($_GET["page_no"] - 1) * $records_per_page;
}
$query2 = $query . " limit $starting_position,$records_per_page";
return $query2;
}
public function paginglink($query, $records_per_page)
{
$self = $_SERVER['PHP_SELF'];
$stmt = $this->db->prepare($query);
$stmt->execute();
$total_no_of_records = $stmt->rowCount();
if ($total_no_of_records > 0) {
?>
<ul class="pagination"><?php
$total_no_of_pages = ceil($total_no_of_records / $records_per_page);
$current_page = 1;
if (isset($_GET["page_no"])) {
$current_page = $_GET["page_no"];
}
if ($current_page != 1) {
$previous = $current_page - 1;
echo "<li><a href='" . $self . "?page_no=1' >First</a></li>";
echo "<li><a href='" . $self . "?page_no=" . $previous . "'>Previous</a></li>";
}
for ($i = 1; $i <= $total_no_of_pages; $i++) {
if ($i == $current_page) {
echo "<li class='active'><a href='" . $self . "?page_no=" . $i . "' >" . $i . "</a></li>";
} else {
echo "<li><a href='" . $self . "?page_no=" . $i . "'>" . $i . "</a></li>";
}
}
if ($current_page != $total_no_of_pages) {
$next = $current_page + 1;
echo "<li><a href='" . $self . "?page_no=" . $next . "'>Next</a></li>";
echo "<li><a href='" . $self . "?page_no=" . $total_no_of_pages . "'>Last</a></li>";
}
?></ul>
<?php
}
}
}
?>
page.php
<?php
//your connection
$host = "localhost";
$user = "root";
$password = "";
$database_name = "";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
include_once'pagination.php';
$paginate = new paginate($pdo);
$search=$_POST['search'];
$Search = "%$search%";
$query = "SELECT * from table where colum1 LIKE ? OR colum2 LIKE ? ";
$records_per_page=10;
$newquery = $paginate->paging($query,$records_per_page,$Search);
$paginate->dataview($newquery,$Search);
$paginate->paginglink($query,$records_per_page);
?>
This should work. Suggestions/comments are welcome.
This is one of the projects I have used the above code to do a pagination :
or use jquery dataTables which will also work perfect
all u need is to download https://datatables.net/
With Datatables, simple download it then add required scripts and css, then on your table add an ID, then initialize datatable
$('#TableID').dataTable();
You might have to do the proper table markup,
<table>
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>Text</td>
</tr>
</tbody>
Sorry , I have a problem with this script :
It's for get tweet with specific id ;
$tweetlist = $twitter->get('https://api.twitter.com/1.1/statuses/show.json?id=694658584664236033');
foreach ($tweetlist->statuses as $key => $value) {
$message = utf8_decode($value->text);
echo $message;
}
Warning: Invalid argument supplied for foreach()
Thank you so much for your help
Nicolas
remove ->statuses, like:
$tweetlist = $twitter->get('https://api.twitter.com/1.1/statuses/show.json?id=694658584664236033');
foreach ($tweetlist as $key => $value) {
$message = utf8_decode($value->text);
echo $message;
}
I would like to run an update query for every row with a specific ID:
e.g.
$ids = array(111, 112, 113);
$query = "UPDATE mytable SET columnName = 'Y' WHERE id = :id1 or id = :id2 or id = :id3";
$stmt->bindParam(':id1', $ids[0], PDO::PARAM_INT);
$stmt->bindParam(':id2', $ids[1], PDO::PARAM_INT);
$stmt->bindParam(':id3', $ids[2], PDO::PARAM_INT);
This works fine if I know there are 3 ids to update, but how would I do this if the number of id fields is variable?
Something like this would do the trick.
$ids = array(111, 112, 113);
$valueString = "";
foreach($ids as $key => $val) {
$valueString .= ":id" . $key . " = " . $val;
if (end($ids) != $val) {
$valueString .= ", ";
}
}
$query = "UPDATE mytable SET columnName = 'Y' WHERE ". $valueString;
foreach($ids as $key => $val) {
$stmt->bindParam(':id' . $key, $val, PDO::PARAM_INT);
}