PHP SQLite3 query not displaying all rows - sqlite

I have a PHP script show below that queries for all rows. The result set only shows one row even though there are more.
mbrlist.php
`<?php
$html = "";
class MyDB extends SQLite3
{
function __construct()
{
$this->open('privdata/helpseekers.db');
}
}
$db = new MyDB();
if ( !$db )
{
echo $db->lastErrorMsg();
}
else
{
$rows = $db->query("SELECT COUNT(id) as count FROM accounts");
$row = $rows->fetchArray(SQLITE3_ASSOC);
$numRows = $row['count'];
echo "Opened database successfully - " . $numRows . " Accounts Found\n";
}
$ret = $db->query("SELECT id,userid,fname,lname,password,email,userrole FROM accounts ORDER BY id ASC");
while ( $rec = $ret->fetchArray() )
{
$html = " <td>{$rec[0]}</td> <td>{$rec[1]}</td> <td>{$rec[2]}</td> <td>{$rec[3]}</td> <td>{$rec[4]}</td> <td>{$rec[5]}</td> <td>{$rec[6]}</td> </tr>\n";
if ( !$rec = $ret->fetchArray() ) break;
}
$db->close();
echo $html;
?>`
So why does it not return more than one row?

In the loop you do :
// Before loop variable html contains ""
// on next line you set into $rec the next row data
// in case there is no more row you exit or not not enter the loop
while ( $rec = $ret->fetchArray() )
{
// anything that was inside $html before this assignment is replaced
// by <td>...</td> of current row
$html = " <td>{$rec[0]}</td> <td>{$rec[1]}</td> <td>{$rec[2]}</td> <td>{$rec[3]}</td> <td>{$rec[4]}</td> <td>{$rec[5]}</td> <td>{$rec[6]}</td> </tr>\n";
// here you get the next row in $rec and test if it is not null
// if it is null you exit the loop
if ( !$rec = $ret->fetchArray() ) break;
// at the end of the loop, the code in while ($rec = ...) is
// executed to get row of next data
}
$db->close();
// here you send the contents of $html to client browser
echo $html;

Related

Wordpress get_results parsing the symbol "&"

I have a strange Thing, where I do not know where the failure is.
$name = "Fast & Furious 8";
$res1 = $wpdb->prepare(
"
SELECT
*
FROM
wp_dbtable
WHERE
filmname = '%s'
LIMIT 1
",
$name
);
$res = $wpdb->get_results( $res1 );
foreach($res as $reseachG) {
}
I have a Problem with the Symbol &. For some reasons it does not pull anything out of my table, even if it should do this.
If I use instead of the variable the text it self, like this:
$res1 = $wpdb->prepare(
"
SELECT
*
FROM
wp_dbtable
WHERE
filmname = '%s'
LIMIT 1
",
"Fast & Furious 8"
);
it works. Also, other text inside the variable works well.
So it seems that prepare, or get_results does not accept this Symbol, or changes it. How can I solve it? I couldn't find any hint on the Internet.
It might not be a PHP-Problem, or a My-SQL-Problem, it might be a Problem of WordPress classes.
Thanks a lot.
The code above is correct. The Problem was, that I pulled the text for the filmname out of the data base. He transformed the & into html-special-chars. So I had to run: htmlspecialchars_decode($filmname);. It was not easy to find, becase every print method printed the correct text.
I found an function on the Internet, which shows me hidden chars and every single real entiti. Maybe it will help some of you also:
function hexdump ($data, $htmloutput = true, $uppercase = false, $return = false){
// Init
$hexi = '';
$ascii = '';
$dump = ($htmloutput === true) ? '<pre>' : '';
$offset = 0;
$len = strlen($data);
// Upper or lower case hexadecimal
$x = ($uppercase === false) ? 'x' : 'X';
// Iterate string
for ($i = $j = 0; $i < $len; $i++)
{
// Convert to hexidecimal
$hexi .= sprintf("%02$x ", ord($data[$i]));
// Replace non-viewable bytes with '.'
if (ord($data[$i]) >= 32) {
$ascii .= ($htmloutput === true) ?
htmlentities($data[$i]) :
$data[$i];
} else {
$ascii .= '.';
}
// Add extra column spacing
if ($j === 7) {
$hexi .= ' ';
$ascii .= ' ';
}
// Add row
if (++$j === 16 || $i === $len - 1) {
// Join the hexi / ascii output
$dump .= sprintf("%04$x %-49s %s", $offset, $hexi, $ascii);
// Reset vars
$hexi = $ascii = '';
$offset += 16;
$j = 0;
// Add newline
if ($i !== $len - 1) {
$dump .= "\n";
}
}
}
// Finish dump
$dump .= $htmloutput === true ?
'</pre>' :
'';
$dump .= "\n";
// Output method
if ($return === false) {
echo $dump;
} else {
return $dump;
}
}
Which shows you the hexa-codes for each char and also every single space, line, special trasformed symbol, or line-braker. It helps to see the real data.
thx to all.

Symfony2 + DBAL. How to use bindValue for multiple insert?

I'm using DBAL and I want to execute multiple insert query. But I have the problem: bindValue() method not working in loop. This is my code:
$insertQuery = "INSERT INTO `phonebook`(`number`, `company`, `user`) VALUES %s
ON DUPLICATE KEY UPDATE company=VALUES(company), user=VALUES(user)";
for ($i = 0; $i < count($data); $i++) {
$inserted[] = "(':number', ':company', ':user')";
}
$insertQuery = sprintf($insertQuery, implode(",", $inserted));
$result = $db->getConnection()->prepare($insertQuery);
for ($i = 0; $i < count($data); $i++) {
$result->bindValue($data[$i]["number"]);
$result->bindValue($data[$i]["company"]);
$result->bindValue($data[$i]["user"]);
}
$result->execute();
As result I received one-line table with fields: :number, :company, :user.
What am I doing wrong?
Thanks a lot for any help!
The problem you're having is that your binding has no way to determine to which placeholder it should be doing the binding with. To visualize it better, think on the final DBAL query you're generating:
INSERT INTO `phonebook`(`number`, `company`, `user`) VALUES
(':number', ':company', ':user'),
(':number', ':company', ':user'),
(':number', ':company', ':user');
When you do the binding, you're replacing all the parameters at the same time, ending up with a single row inserted.
One possible solution would be to give different parameter names to each row and then replace each one accordingly.
It would look like something similar to this:
public function randomParameterName()
{
return uniqid('param_');
}
...
$parameters = [];
for ($i = 0; $i < count($data); $i++) {
$parameterNames = [
'number' => $this->randomParameterName(),
'company' => $this->randomParameterName(),
'user' => $this->randomParameterName(),
];
$parameters[$i] = $parameterNames;
$inserted[] = sprintf("(':%s', ':%s', ':%s')",
$parameterNames['number'],
$parameterNames['company'],
$parameterNames['user']
);
}
$insertQuery = sprintf($insertQuery, implode(",", $inserted));
$result = $db->getConnection()->prepare($insertQuery);
foreach ($parameters as $i => $parameter) {
$result->bindValue($parameter['number'], $data[$i]["number"]);
$result->bindValue($parameter['company'], $data[$i]["company"]);
$result->bindValue($parameter['user'], $data[$i]["user"]);
}
You could probably extend your $data variable and incorporate the new parameter names into it. This would remove the need of yet another array $parameters to hold reference to the newly created parameter names.
Hope this helps
There is another alternative:
$queryStart = "INSERT INTO {$tableName} (" . implode(', ', array_keys($buffer[0])) . ") VALUES ";
$queryRows = $params = $types = [];
foreach ($rowBuffer as $row) {
$rowQuery = '(' . implode(', ', array_fill(0, count($row), '?')) . ')';
$rowParams = array_values($row);
list($rowQuery, $rowParams, $types) = SQLParserUtils::expandListParameters($rowQuery, $rowParams, $types);
$queryRows[] = $rowQuery;
$params = array_merge($params, $rowParams);
}
$query = $queryStart . implode(', ', $queryRows);
$connection->executeQuery($query, $params, $types);

wp_set_object_terms() return invalid_taxonomy

i tried to set the taxonomy of a post but it always return invalid_taxonomy error.
$categorys_ids = wp_set_object_terms($post_id, $categorys, 'categorie-video');
error_log('categorys brut = ' . $data['category'] .'postid '.$post_id.'categorys = ' . json_encode($categorys_ids));
//byme
if (is_wp_error($categorys_ids)) {
error_log('categorys =There was an error somewhere and the terms couldn\'t be set');
} else {
error_log('categorys =Success! The post\'s categories were set.');
}

How to execute a php loop in an andWhere clause using QueryBuilder?

I would like to execute this type of query using QueryBuilder in my FakeRepository.php (it's for a search form where the user can check some boxes).
if (sizeof($p['types']) > 0) {
$qb->andWhere(
foreach ($p['types'] as $type_id)
{'type.id=' .$type_id.' OR ' }
'1=0');
}
But I have an error with my syntax but I don't know how to fix it :
Parse error: syntax error, unexpected T_FOREACH, expecting ')' in /MyBundle/Entity/FakeRepository.php
Thanks a lot for your help
You need to first construct your OR condition and then pass it to the query builder
$first = true;
$orQuery = '';
foreach ($p['types'] as $type_id)
if ($first) {
$first = false;
} else {
$orQuery .= ' OR ';
}
$orQuery .= 'type.id=' .$type_id;
}
$qb->andWhere($orQuery);
You can also resove this problem:
$arr = array();
foreach ($p['types'] as $type_id){
$arr[] = $qb->expr()->orX("type.id = $type_id");
}
$qb->andWhere(join(' OR ', $arr));
Another solution to keep QueryBuilder functionality
$orX = $qb->expr()->orX();
foreach ($types as $key => $type) {
$orX->add($qb->expr()->eq('types', ':types'.$key));
$qb->setParameter('types'.$key, $type->getId());
}
$qb->andWhere($orX);

Wordpress - Excerpt character alternative?

I'm totally new to WordPress so be easy :)
I the following code in a template:
<?php excerpt(20);?>
What this does is limit the text with 20 words. I am now wondering if there is some sort of similar function that limits by characters instead of words?
Thanks!
I use this:
add_filter('excerpt_length', 'my_excerpt_length');
function my_excerpt_length($length) {
return '500';
}
function better_excerpt($limit, $id = '') {
global $post;
if($id == '') $id = $post->ID;
else $id = $id;
$postinfo = get_post($id);
if($postinfo->post_excerpt != '')
$post_excerpt = $postinfo->post_excerpt;
else
$post_excerpt = $postinfo->post_content;
$myexcerpt = explode(' ', $post_excerpt, $limit);
if (count($myexcerpt) >= $limit) {
array_pop($myexcerpt);
$myexcerpt = implode(' ',$myexcerpt).'...';
} else {
$myexcerpt = implode(' ',$myexcerpt);
}
$myexcerpt = preg_replace('`\[[^\]]*\]`','',$myexcerpt);
$stripimages = preg_replace('/<img[^>]+\>/i', '', $myexcerpt);
return $stripimages;
}
And then in my theme file, I just call it in with:
better_excerpt('50') //50 being how many words I want
Useful for custom plugins/widgets too.
Wordpress doesn't support the character delimiter for the excerpt method, there's a plugin called Advanced Excerpt that does. After installing you can call the_advanced_excerpt('length=20&use_words=0')
I use this in my functions.php:
function truncate ($str, $length=10, $trailing='...'){
// take off chars for the trailing
$length-=mb_strlen($trailing);
if (mb_strlen($str)> $length){
// string exceeded length, truncate and add trailing dots
$str = mb_substr($str,0,$length);
$str = explode('. ',$str);
for( $i=0; $i<(sizeof($str)-2); $i++ ):
$newstr .= $str[$i].". ";
endfor;
return $newstr;
} else{
// string was already short enough, return the string
$res = $str;
}
return $res;
}
It should truncate to a character count, but then truncate back further to the last period before the truncation. It does get problematic when your excerpt includes links, however, or other markup - in other words, it's best to use the Excerpt field in the post rather than auto-excerpting with this function, because you can't use HTML in the excerpt field.
Please use this code for limiting post content...
<?php substr($post->post_content, 0, xy); ?> ...
Change the limit of XY....

Resources