Build an array using foreach - php

I have this array:
$arrUsers = array(
array('username' => 'admin', 'password' => 'admin123')
);
I just want to build a similar copy of this array using data from PDO MySQL Table, with foreach.. I've tried this, but doesn't work
$arrUsers = array();
foreach ($users as $i){
array_push($arrUsers, array('username' => $i['username'], 'password' => $i['password']));
}
returns a different array structure..
--EDITED:
MY PDO CODE
$sql_buscaUsuarios = "SELECT username, password FROM users";
try{
$query_buscaUsuarios = $conecta->prepare($sql_buscaUsuarios);
$query_buscaUsuarios -> execute();
$usuarios = $query_buscaUsuarios->fetch(PDO::FETCH_OBJ);
}
catch(PDOexception $erro_buscaEndereco){
echo 'er2'.$erro_buscaEndereco->getMessage();
}

Related

How to get a single value from MongoDB using PHP?

So I have the following code to get a document from a collection in my database:
$manager = new MongoDB\Driver\Manager('mongodb+srv://<username>:<password>#cluster0.hyqa4.mongodb.net/academic?retryWrites=true&w=majority');
$filter = ['username' => $uname];
$options = ['projection' => ['_id' => 0]];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery("academic.users", $query);
foreach($cursor as $document) {
print_r($document);
}
I'm able to successfully retrieve a document by searching for the username, so if $uname is "Jon", I get the following output:
stdClass Object ( [username] => Jon [email] => Jon#mail.com [passwd] => pass123 )
However, what I want to do is just return a single value from the document, so if I wanted to get the value for email, it would return:
Jon#mail.com
...so then I could store that value as a variable.
How would I do this?
Std class objects can be accessed via -> operator. So you can user $document->email to access individual email. Is this what you are looking for
$manager = new MongoDB\Driver\Manager('mongodb+srv://<username>:<password>#cluster0.hyqa4.mongodb.net/academic?retryWrites=true&w=majority');
$filter = ['username' => $uname];
$options = ['projection' => ['_id' => 0]];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery("academic.users", $query);
foreach($cursor as $document) {
print_r($document->email);
}

Turn a array into a variable for send in PHPMailer

Im trying to turn a array that haves another array from a SQL select into a unique variable to send it for users by PHPMailer, I tried to place the array on variable of PHPMailer so didnt works, thats why Im trying this way that looks a little bit difficult
public static function getUsersByEmail($email) {
$sql = DB::prepare(
"SELECT username FROM users WHERE email=:email ORDER BY id LIMIT 10"
);
$sql->bindParam('email', $email);
$sql->execute();
$accounts = $sql->fetchAll(PDO::FETCH_ASSOC);
return $accounts; // its array
}
public function recoverUsername($email) {
if (User::emailHasAccounts($email) == true) {
$accounts = [User::getUsersByEmail($email)];
$str = implode(",", $accounts); // imploding array
$mail = new Mail([
'email' => $email,
'subject' => SITENAME,
'template' => 'accountslist',
'variables' => json_encode([
'email' => $email,
'accountList' => $str,
'date' => date('d/m/y h:i')
]),
'time' => time(),
'next_attemp' => time(),
'attemps' => 0,
'status' => 0
]);
// $mail->dbInsert();
return true;
} else {
echo "erro";
return false;
}
}
Solution (for PHP 5.5 <)
$accounts = getAccounts();
$rr = array_column($accounts, 'username');
$array = implode(',', $accounts);
$getaccounts = array_map(function ($accounts) {
return $accounts['username'];
}, $accounts);
$var = implode('<br>', $getaccounts);

Retrieve fields of Mongo collection in PHP

I tried using the fields() method on the cursor:
<?php
$mongo = new Mongo("mongodb://localhost");
print_r($mongo);
$db = $mongo->test;
// access collection
$collection = $db->test;
// execute query
// retrieve all documents
print_r($test);
$cursor = $collection->find();
print_r($cursor);
$fields = $cursor->fields(array("summary" => true));
print_r($fields);
The output is:
Mongo Object ( [connected] => 1 [status] => [server:protected] => [persistent:protected] => )
MongoCursor Object ( )
MongoCursor Object ( )
Looks like the driver and the connection work but I can't retrieve the distinct summarization of the fields.
Assume that we have access to mongodb database with the name db, are going to retrieve data from MyCollection and use MongoDB\Driver\Manager:
$manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
Then we retrieve data in this case by name with a limit 2 documents and want to get only fields name, age and address among many others. Projection option can be used to specify which fields should be returned using 0 to exclude and 1 to include:
$filter = ['name' => 'John'];
$options = [ 'projection' => ['_id' => 0, 'name' => 1, 'age' => 1, 'address' => 1], 'limit' => 2 ];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
If we need to get all columns, then we simply omit projection option at all as the following:
$filter = ['name' => 'daniel'];
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
const HOST = 'localhost';
const PORT = 27017;
const DBNAME = 'test';
const COLLECTION = 'test';
$connectionString = sprintf('mongodb://%s:%d', HOST, PORT);
try {
$connection = new Mongo($connectionString);
$database = $connection->selectDB(DBNAME);
} catch (MongoConnectionException $e) {
throw $e;
}
$collection = $database->selectCollection(COLLECTION);
try{
$query = array();
$specifyKey = array("summary" => true);
$cursor = $collection->find($query , $specifyKey);
}catch(MongoException $e) {
die('Failed to find One data '.$e->getMessage());
}catch (MongoCursorException $e) {
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
}
while ($cursor->hasNext()){
$nextCursor = $cursor->getNext();
//process next cursor
}
After the $cursor variable try an foreach instead. It goes through the cursor results.
foreach($cursor as $document) {
var_dump($document);
}

Is there a way to return all database columns automatically in CodeIgniter?

This is how I currently do a query and return a dataset in CodeIgniter:
$sql = "SELECT `user_id`, `username`
FROM `users`
LIMIT 10";
$query = $this->db->query($sql);
$users = array();
foreach($query->result() => $row) {
$users[] = array(
'user_id' => $row->user_id,
'username' => $row->username
);
}
return $users;
As you can see I explicitly write what fields I want to return:
$users[] = array(
'user_id' => $row->user_id,
'username' => $row->username
);
Is there a way to have this be done automatically. So all fields that are selected in the sql query will be listed as the key and value of the array being returned?
Yes, there is. Use result_array().
foreach ($query->result_array() as $row)
...
You can find out more about this here.

About creating an array at php

I am having trouble at creating a specific array.
What i want is to pull the info for my members (from mysql database) and then store them to an array.
The array should be like this:
$members = array(
'John' => array('avatar' => '/images/avatar/ji.jpg', 'country' => 'uk.'),
'Nick' => array('avatar' => '/images/avatar/nick.jpg', 'country' => 'italy.'),
);
etc..
so i pull the name,avatar url and country from the db and then i store them in to the previous array.
My question is, how could i create this array?
Thanks in advance!
About creating an array at php.
Something like this should work:
$members = array();
$q = mysql_query("SELECT name , avatar, country from table");
while($row = mysql_fetch_assoc($q)){
$array = array("avatar" => $row['avatar'] , "country" => $row['country']);
$members[$row['name']] = $array;
}
Using PDO:
$members = array();
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$sql = "SELECT name, avatar, country FROM members";
foreach ($conn->query($sql) as $row) {
$temp = array('avatar' => $row['avatar'], 'country' => $row['country']);
$members[$row['name']] = $temp;
}

Categories