Skip results inside a foreach loop - pdo - php

In my database I store email addresses. In the foreach loop how can I skip all email addresses that has #sample.com.ru?
$sql = "SELECT * FROM myMovieCustomers";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row) {
//skip if $row['email'] contains #sample.com.ru{
//do someting with these
//}
}

it's more efficient to do filtering at the database level for a couple of reasons
you're not wasting network resources transmitting unneeded data across the wire
with a well indexed table, the DBMS will be faster at making the search than php will with the result data
as is pointed out in the comments and other answers, you can use the LIKE operator
$sql = "SELECT * FROM myMovieCustomers WHERE email NOT LIKE '%#sample.com.ru'";

You can achieve what you want by using php function strstr() like below:
$all = array(
'name' => array('Thanga','Kima','Zara'),
'email'=> array('thanga#gmail.com','kima#gmail.com','zara#sample.com.ru')
);
echo '<pre>';
print_r($all);
foreach($all as $key=>$val):
foreach ($val as $k=>$v):
if(strstr($v,'#')=='#sample.com.ru'){
}else{
echo $v;
}
endforeach;
endforeach;

Just change the first line...
$sql = "SELECT * FROM myMovieCustomers WHERE email NOT LIKE'%#sample.com.ru'";

Related

How can I check it appears twice and keep the email address from the database in the foreach loop?

Hello i have one selection from database and all records i store in variable $list now.. In my database i have more account with same email address how to store in variable $list one of this..
I have this code:
<?php foreach($list as $li){
echo $li['email'].'<br>';
}?>
And in mysql i have this:
public function getEmailAddress(){
$sql = "SELECT email FROM account.account";
$stmt=$this->o_db->prepare($sql);
$stmt->execute(array(':apply' => $apply));
$result = $stmt->fetchAll();
return $result;
}
In query mysql selection I need a condition or in php code?
If what you are asking is a way to skip any duplicate email addresses, here is what you can do.
Just use the DISTINCT keyword in your query.
$sql = "SELECT DISTINCT email FROM account.account";
Alternatively, you could use PHP.
<?php
$processed_emails = [];
foreach($list as $li){
$email = $li['email'];
if(!in_array($email, $processed_emails)) {
echo "{$email}<br>";
$processed_emails[] = $email;
}
}
?>
Alternatively, you could use PHP's array_unique() function.
<?php
$list = array_unique($list);
foreach($list as $li){
echo $li['email'].'<br>';
}
?>
Note:
Your code is likely failing because of this: $stmt->execute(array(':apply' => $apply));. You are sending a parameter with your query, but your query has no parameters. Since you have no parameters, you also do not need $stmt=$this->o_db->prepare($sql);.
Your code should then be:
$sql = "SELECT email FROM account.account";
$stmt=$this->o_db->query($sql);
$result = $stmt->fetchAll();

Php - Array to string conversion

I want to output all records in my database. So far so good, but when I loop through it, php gives me an error " Array to string conversion ".
I added an index to the array but then it does just output obviously the first or secound ( etc. ) column.
$conn = new PDO("mysql:host=localhost;dbname=database","root","");
$stmt = $conn->prepare('SELECT * FROM de');
$stmt ->execute();
$result = $stmt ->fetchAll();
if (is_array($result) || is_object($result))
{
foreach ($result[0] as $value)
{
echo "<table><tr><td>'$value'</td></tr></table>";
}
}
So, with the index, it does work. But I need all records, not just one.
I appreciate every comment and help!
I would start with a nested loop. I also wonder if you want a table for every value
$conn = new PDO("mysql:host=localhost;dbname=database","root","");
$stmt = $conn->prepare('SELECT * FROM de');
$stmt ->execute();
$result = $stmt ->fetchAll();
if (is_array($result) || is_object($result))
{
foreach ($result as $row){ //Go through every row in the result
echo('<table>');
foreach ($row as $value){ //Go through every value in the row
echo "<tr><td>'$value'</td></tr>";
}
echo('</table>');
}
}
This will print every row as a new table, but you can search out the variation you want.
A nested foreach loop should work.
foreach ($result as $values)
{
foreach ($values as $value) {
echo "<table><tr><td>'$value'</td></tr></table>";
}
}
An alternative to nested loops, if you know the number of fields and said number is constant for each execution; A state that's found in most situations; You can use vsprintf () to print out the rows.
Quick example:
$result = {{'John', 'Doe'}, {'Sarah', 'Jane'}};
$output = '<table>';
foreach ($result as $row) {
$output .= vsprintf ("<tr><td>%s</td><td>%s</td></tr>\n", $row);
}
echo $output."</table>";
Cuts down a bit on the code, and quite a bit on the code complexity. The template for the rows themselves can also be extracted to a variable (or template view), outside of the loop, to make the code even cleaner.

Order after executed?

Im trying to do a PHP script where it order users based on a point system. Problem is that the points is calculated after I execute the users. Like this:
$getScore = $db->prepare("SELECT * FROM `users`");
$getScore->execute();
$results = $getScore->fetchAll();
foreach($results as $row):
$likes = $get->likes("user", $row["id"]);
$subscribers = $get->subscribers("user", $row["id"]);
$score = $get->score($likes, $subscribers, $row["date"]);
echo $row["username"];
endforeach;
Without having another execution how do I order the results? I want the user with highest value on $score to be shown first. I've tried alot of things but without succession.
Thanks in advance!
You can implement this different ways.
If you have already loaded all the data from the databse you can order them using PHP.
Custom sorting can be done using usort.
PHP.net - usort documentation
Maybe you could use something like this:
$users = array();
// Load all the users and calculate scores
foreach($results as $row):
$users[$row["username"]] = $get->score($likes, $subscribers, $row["date"]);
endforeach;
// Sort users based on score
sort($users);
// Output users, sorted by score
foreach($score as $key => $row):
echo $key, " score:", $score;
endforeach;
If you would like to use a more complex data structure, all you have to do is implement the special comparision to ensure ordering by score with usort.
If you store the points in the database, then you could use a special query including an ORDER BY clause, this way returning the users already ordered.
I think using the DBMS to order the users would result in a more scalable solution. If you have really high number of users, it is not going to perform well to sort all the users each page load.
First, sorry for suggesting another execution flow. Next, this is my solution:
$getScore = $db->prepare("SELECT * FROM `users`;");
$getScore->execute();
$results = $getScore->fetchAll();
// Result is something like [rownum][colomname]
array_walk_recursive($results, function($item, $key) {
$id = $item["id"];
$date = $item["date"];
$arr = array();
$arr['likes'] = $get->likes("user", $id);
$arr['subscribers'] = $get->subscribers("user", $id);
$arr["score"] = $get->score($arr["likes"],
$arr["subscribers"],
$date);
$item = array_merge($item, $arr);
});
In this code you get the results from your database. Next you calculate things like the score and you add this to the array.
To sort this array on the score you can use the PHP multisort function (http://php.net/manual/en/function.array-multisort.php):
foreach ($results as $key => $row) {
$score[$key] = $row["score"];
}
array_multisort($score, SORT_DESC, $results);
When you're looping your loop to print the data for example you can do this:
foreach($results as $row) {
$likes = $row["likes"];
$subscribers = $row["subscribers"];
$score = $row["score"];
echo("your stuff over here");
}
Good luck!

Nesting foreach loops with PDO statements

I'm trying to nest foreach loops with PDO statements (this previously worked for me in mysql,btw). The first example works and the second one doesn't. However I'd prefer not to run a SQL query every time (isn't that the point of PDO?) and would prefer to use something more like example 2. However, it doesn't 'nest' the loop inside the other, it seems, rather it runs the first then the next.
Example 1)
foreach($db->query('SELECT country FROM db GROUP BY `country`') as $row1) {
echo $row1['country']."<br/>";
foreach($db->query('SELECT * FROM db') as $row2) {
if ($row1['country']==$row2['country']){
echo $row2['name']."<br/>";
}
}
}
Example 2)
$cntry = $db->query('SELECT country FROM db GROUP BY `country` ');
$rslts = $db->query('SELECT * FROM db');
foreach ($cntry as $row1) {
echo "<div id='".$row1['country']."'>".$row1['country']."<br/>";
foreach($rslts as $row2) {
if ($row1['country']==$row2['country']){
echo $row2['name']."<br/>";
}
};
echo "</div>";
}
(isn't that the point of PDO?)
No. The point of PDO is to send your query to database server and to return the results back. But PDO cannot reduce the number of queries executed.
So, here goes the proper solution:
$stmt = $db->query('SELECT country, name FROM db ORDER BY country, name');
$data = $stm->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
foreach ($data as $country => $row)
{
echo $country."<br/>\n";
foreach ($row as $name)
{
echo $name."<br/>\n";
}
}
As a matter of fact, fetchAll() is just a syntax sugar for the code like this:
$data = array();
while ($row = $stmt->fetch())
{
$data[] = $row;
}
it just creates a regular PHP array out of query result. And of course you can loop over this array as many times as you wish. Means you an always replace fetchAll() with manual looping over results, and of course you may group the results whatever way you wish.
While using foreach on $stmt is just a syntax sugar again, intended to confuse PHP users. Because $stmt is not an array but a way more complex structure.
not sure, but as I remember it would be like this
$cntry = $db->query('SELECT country FROM db GROUP BY `country` ')->fetchAll (PDO::FETCH_COLUMN);
$rslts = $db->query('SELECT * FROM db')->fetchAll(PDO::FETCH_COLUMN);
foreach ($cntry as $row1) {
echo $row1['country']."<br/>";
foreach($rslts as $row2) {
if ($row1['country']==$row2['country']){
echo $row2['name']."<br/>";
}
}
}

php foreach loop only returns first character of each string

I have the below code. It is only returning the first charater of a string.
$conn = Mage::getSingleton('core/resource')->getConnection('connection_write');
$str = 'something to search for';
$fields = 'content_field1, content_field2, content_field3, content_field4';
$idFields = 'id_field1, id_field2, id_field3, id_field4';
$tables = 'table1, table2, table3, table4';
$table = explode(', ', $tables);
$field = explode(', ', $fields);
$rowId = explode(', ', $idFields);
$i=1;
while ($i<4) {
$f = $field[$i];
$id = $rowId[$i];
$sql = $conn->select()->from($table[$i], array($f, $id))->where($f . " LIKE ?", '%' . $str . '%');
$result = $conn->fetchRow($sql);
foreach ($result as $row) {
var_dump($row[$id]);
}
$i++;
}
However, if I use var_dump($row); the entire string from both the id fields and the content fields are outputted.
Can anyone explain to me what I am doing wrong?
Thanks in advance.
However, if I use var_dump($row); the entire string from both the id fields and the content fields are outputted.
well, why do you use var_dump($row[$id]); which exactly equals to "take $id'th char from $row string" then?
foreach ($result as $row) {
$result is a list of rows you selected from the table. Each $row is a string.
$row[$id] simply selects the $id'th character from this row string.
I believe the problem has to do with the fact that $result is an array (possibly an associative array) of strings. (I'm not familiar with Mage, but I'm assuming that fetchRow() returns only a single row and not all of your rows.)
Therefore, what's happening is you've probably got something like this:
$result = array("tom","dick","harry");
When you run foreach($result as $row), $row looks like "tom", "dick", and "harry" on each iteration.
Because $row is a string, calling $row[$id] makes PHP attempt to get get a single character from the $row string. Because it's expecting $id to be an integer in this case, it's probably interpreting "id_field1" as 0, which will end up returning the first character of your string.
I'm not exactly sure what you're trying to get back, but most likely this can be solved by changing your foreach section to be something like...
foreach ($result as $resultColumn) {
var_dump($resultColumn);
}
->fetch() is not needed when fetching data by using foreach statement like in your code (Please see examples below). If you use ->fetch() unnecessarily, this situation often occurs (I experienced this too..)
foreach statement and while statement have the following relationship. Please consider rewriting the code, referring to this:
<?php
$stmt = $pdo->query('SELECT * FROM Entry');
while ($row = $stmt->fetch()) {
echo $row['title'], $row['content'];
}
//this while statement above is equivalent to the foreach statement below
foreach ($stmt as $row) {
//->fetch() is not needed for foreach statement!
echo $row['title'], $row['content'];
}

Categories