How do I fill a PHP array with data from MySQL? - php

I'm using the Twilio API to send sms. I'm trying to change it so that I can send to a list of recipients from mysql results.
The example code given is:
$people = array(
"+14155551212" => "First Lastname",
);
My code is:
$people = array(
while($res = mysql_fetch_array($usersphone)) {
$people[$res['UserMobile']] = $res['UserFirstName'];
}
);
The syntax is bad but I can't figure out where.

You can't put control structures into arrays.
$people = array();
while ($res = mysql_fetch_array($usersphone)) {
$people[$res["UserMobile"]] = $res["UserFirstName"];
};
Also, there's a ton of posts here on SO that will tell you all about not using the mysql_* functions anymore, since they're deprecated.

You have logic in your array definition. You should define the array, and then populate it with the while.
// define the array
$people = array();
while($res = mysql_fetch_array($usersphone)) {
// populate key with mobile and value with name
$people[$res['UserMobile']] = $res['UserFirstName'];
}

Related

Placing SQL query results into one array

I have this PhP script:
<?php
$gregorianMonth = date(n);
$gregorianDay = date(j);
$gregorianYear = date(Y);
$jdDate = gregoriantojd($gregorianMonth,$gregorianDay,$gregorianYear);
$hebrewMonthName = jdmonthname($jdDate,4);
$hebrewDate = jdtojewish($jdDate);
list($hebrewMonth, $hebrewDay, $hebrewYear) = split('/',$hebrewDate);
?>
<?php
$table_name = "candle_number";
$data = $wpdb->get_results( "SELECT email FROM `{$table_name}` WHERE `datehebrew` LIKE '%%$hebrewDay%%' AND `datehebrew` LIKE '%%$hebrewMonth%%' AND date_pref = \"hebrew\"");
foreach( $data as $rs ){
echo "
<p>{$rs->email}</p>
";hat I can
$i++;
}
?>
And what I was initially thinking was to use a foreach loop with the CURL Mailchimp API to send each email to my endpoint, kind of a one off.
BUT - I know that the foreach might not loop process and it's not very clean. I think the BETTER solution would be to have every result put into an array then send THAT array in the curl, because the MC API will accept it.
I am still kind of a novice though so this is where I am stuck. So how can I take those results from my query and put them into one string?
Try:
//create blank array
$final_output = array();
foreach( $data as $rs ){
//add data to array in next index.
final_output[] = $rs->email;
$i++;
}
//at this point send your data array wherever you want.
print_r($final_output);
If you want to convert your data to string use:
echo json_encode($final_output);

mysql only fetches single row rather than all

Hello in my php code mysql only fetches 1 result which is in the last rather than all please help me why its doing like this here is my code
$requesthost = "SELECT * FROM tblvhost";
$reshost = mysql_query($requesthost);
while($rowhost=mysql_fetch_array($reshost)) {
$hostvid = $rowhost['vh_id'];
$hostname = $rowhost['vh_name'];
}
You’re overriding the data within each loop iteration:
while($rowhost=mysql_fetch_array($reshost)) {
$hostvid = $rowhost['vh_id']; // overwritten
$hostname = $rowhost['vh_name']; // overwritten
}
To collect all the data you probably want to append them to an array:
$hostvid = array();
$hostname = array();
while($rowhost=mysql_fetch_array($reshost)) {
$hostvid[] = $rowhost['vh_id']; // insert into array
$hostname[] = $rowhost['vh_name']; // insert into array
}
You are overwrite your variables in your loop. Store them into an array.
while ($rowhost = mysql_fetch_array($reshost)) {
$row[] = array(
'hostvid' => $rowhost['vh_id'],
'hostname' => $rowhost['vh_name']
);
}
var_dump($row);
this is a good question plus its a learning curve for the ones that are new that run into these types of issues
you're code
$requesthost = "SELECT * FROM tblvhost";
$reshost = mysql_query($requesthost);
while($rowhost=mysql_fetch_array($reshost)) {
$hostvid = $rowhost['vh_id'];
$hostname = $rowhost['vh_name'];
}
looks good, but what you are doing with or how are you applying hostvid? or hostname? you can just do
while($rowhost=mysql_fetch_array($reshost)) {
$rowhost['vh_id']; //do something with the var that's getting mysql field data
$rowhost['vh_name']; //same applies here. using $rowhost will continue to to provide data depending on what you have in the db. so you're OK.
}
if you want to store the data in an array for later use outside of the loop you can follow what #mudasobwa posted. good answer.

Reorder array from mysql query

I have an array returned from MYSQL query with 2 LEFT JOINs.
Question is: "Is there another way for writing the code below?". I got the code but I want a more clear way of it just to understand what happens inthere.
CODE:
$result = array();
while ($resultArr = mysqli_fetch_assoc($booksAndAuthors)) {
$result[$resultArr['book_id']] ['book_name'] = $resultArr['book_title'];
$result[$resultArr['book_id']] ['author'][] = $resultArr['author_name'];
print_r($result);
}
With the extract() function you can make the data in the result into variables. I have put the example below inside a function, so they will be local variables.
function getBooksAndAuthors($queryResult)
{
while ($data = mysqli_fetch_assoc($queryResult))
{
extract($data);
$BooksAndAuthors[$book_id] = array('book_name' => $book_title,
'author' => $author_name);
}
return $BooksAndAuthors;
}
This makes the code a lot more readable. You will, of course, have to know which columns there are in your database table. I also left out the extra '[]' for the author.
Here's how I recommend writing it, because I don't think you should depend on automatic creation of intermediate arrays.
$result = array();
while ($row = mysqli_fetch_assoc($booksAndAuthors) {
$bookid = $row['book_id'];
if (!isset($result[$bookid])) {
# First time we see this book, create a result for it
$result[$bookid] = array('book_name' => $row['book_title'],
'author' => array());
}
# add this author to the result entry for the book
$result[$bookid]['author'][] = $row['author_name'];
}
It's essentially equivalent, but I think it also makes the logic clearer.

Creating token list from mysql query into json

i have recently started using the twitter typeahead addon for a new project and have hit a bit of a snag, i am querying 2 columns in 1 table for the data to search, i have it working fine when just searching 1 column however when moving to two i believe i need to start using tokens for the search.
however i cant figure out a way to add in tokens into my array to then encode them to json and return back to the search
this is my code so far:
$dbh = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', '');
$stmt = $dbh->prepare('SELECT NAME, CLID FROM customer');
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row_array['NAME'] = $row['NAME'];
$row_array['CLID'] = $row['CLID'];
$row_array['tokens'] = "";
$results[] = $row_array;
}
$json = json_encode($results);
echo $json;
return $json;
the tokens line is going into the array fine however im not sure on how to format it, i understand it needs to be in the format of
tokens:[
"token1", "token2", "token3"
]
the tokens will be the values of the NAME and CLID, how can i go about creating the tokens to ideally look like this:
{
name: "name",
CLID: "CLID",
tokens: [
"name1", "clid1", "name2", "clid2", "name3", "clid3"...
]
}
Managed to figure it out by reading up some more, to create a nested json element you need to add in through an array within an arry
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row_array['NAME'] = $row['NAME'];
$row_array['CLID'] = $row['CLID'];
$row_array['tokens'] = array($row["NAME"],$row["CLID"]); //create new array and add the tokens you want
$results[] = $row_array;
}

PHP multidimensional array from database results

I'm a bit new to multidimensional arrays, and would like to see if I'm doing it right. preferably, I'd like to name the arrays within the main array for ease of use.
$unique_array = array(
username=>array(),
user_id=>array(),
weeknumber=>array()
);
and then I have a while loop which checks some database results:
while($row = mysql_fetch_array($query)) //yes, I know mysql is deprecated
{
$unique_array[] = username=>$row['username'], user_id=>$row['user_id'], week number=>['weeknumber'];
}
I'm not sure if I am placing the values in the array from within the while loop correctly, or if it needs to be done some other way. I couldn't find any resources I could easily understand on SO or elsewhere to deal with query results within a named array within a multidimensional array.
EDIT FOLLOW UP QUESTION: I also need to check the array for duplicate values, because there will be multiple values that are exactly the same, but I only want one of them.
Any help is appreciated!
EDIT SOLUTION:
By modifying the answer I was able to create code to fit my needs.
Array initialization:
$unique_array = array(
'username'=>array(),
'user_id'=>array(),
'weeknumber'=>array()
);
Building the array from within a while loop:
while($row = mysql_fetch_array($query))
{
$unique_array[] = array('username'=>$row['username'], 'user_id'=>$row['user_id'], 'weeknumber'=>$row['weeknumber']);
}
And finally, I need to make sure the array values are unique (there are duplicates entries as a result of database and query limitations), after the while loop I have:
print_r(multi_unique($unique_array));
Is the top level an associative array or a numeric array?
If it is an associative array, it should have structure like this:
$unique_array = array(
'username'=>array('John','Mike',...),
'user_id'=>array(1,2,3,...),
'week_number'=>array(1,2,3,...)
);
Or if it is a numeric array, it should have structure like this:
$unique_array = array(
array('username'=>'John', 'user_id'=>1, 'week_number'=>1),
array('username'=>'Mike', 'user_id'=>2, 'week_number'=>2),
array('username'=>'Sam', 'user_id'=>3, 'week_number'=>3),
...
)
for the first type use the code below:
while ($row = mysql_fetch_assoc($query)) {
$unique_array['username'][] = $row['username'],
$unique_array['user_id'][] = $row['user_id'],
$unique_array['week_number'][] = $row['week_number'],
}
for the second type, it is something like your code. But there are some syntax problems:
while($row = mysql_fetch_array($query)) //yes, I know mysql is deprecated
{
$unique_array[] = array('username'=>$row['username'], 'user_id'=>$row['user_id'], 'week_number'=>$row['weeknumber']);
}

Categories