In php how to display mysql results? - php

I have a mysql table in which I keep e-mail addresses. The structure is as follows:
id || email
However, how do I actually output those e-mail addresses, separated by commas, in php?
Thanks in advance for your help!

Use:
<?php
$query = "SELECT GROUP_CONCAT(t.email) AS emails
FROM YOUR_TABLE t"
// Perform Query
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo $row['emails'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
References:
mysql_query
GROUP_CONCAT

Third hit on Google for "php mysql": http://www.freewebmasterhelp.com/tutorials/phpmysql
You probably need to read up on the basics, it's not complicated and will only take a few minutes to glance over it and get you started.

Option 1:
$sql = "SELECT GROUP_CONCAT(email ORDER BY email ASC SEPARATOR ', ') AS emails FROM emails";
$res = mysql_query($sql);
list($emails) = mysql_fetch_row($res);
echo $emails;
Option 2, so you can do more with all the emails later on:
$emails = array();
$sql = "SELECT email FROM emails ORDER BY email ASC";
$res = mysql_query($sql);
while ($r = mysql_fetch_object($res)) {
$emails[] = $r->email;
}
// as a list
echo implode(', ',$emails);
// or do something else
foreach ($emails as $email) {
// ...
}

Do something like:
while ($output = mysql_fetch_array($query_results)) {
echo $output['id'] . ", " . output['email'];
}

Related

add values with PHP

I have a database table with two fields both id and value and I'd like to add the two entries for value together and then echo out the total of the sum.
So far I've been able to display both entries for value by using the following.
function showTotal() {
global $connection;
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
if (!$result) {
die('Query FAILED' . mysqli_error());
} else if (isset($failed)) {
echo "Failed";
}
while ($row = mysqli_fetch_assoc($result)) {
$value = $row['value'];
echo "$value";
}
}
What I really want is these values added together rather than displaying alongside each other.
Thanks
James
I haven't tested it, but something like this could potentially be a one-liner.
echo array_sum( array_column( mysqli_fetch_all( $result, MYSQLI_ASSOC), 'value' ) );
That said, if you do not need all the results, this is a better option:
$result = mysqli_query( 'SELECT SUM(value) AS mysum FROM table' );
echo mysqli_fetch_array($result, MYSQLI_ASSOC)['mysum'];
Using php you could sum up the values like so:
$value = 0;
while ($row = mysqli_fetch_assoc($result)) {
$value += $row['value'];
}
echo $value;
While I personally would opt to go with the solution offered by #jm, PHP does offer another way with its array_sum(), as follows:
<?php
$value = 0;
while ($row[] = mysqli_fetch_assoc($result)) {}
echo array_sum($row['value']);
See Manual
Note: you could change the fetching of the result by using mysqli_fetch_all, if you have the MySQL native driver; see here.

Setting PHP variables from Database Using MYSQL

Looking to select multiple values from the database and echo with PHP. (Newbie)
For instance:
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 4
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 5
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 6
How would I set the variables.. something along the lines of this using MYSQLi for multiple variables?
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
Truly appreciate any help.
Yes. Though if your query returns multiple rows, you'll need to use:
while ($row = mysqli_fetch_assoc($result))
{
//do something here
}
you need to make a loop for , foreach or a while loop
ex
while ($row = mysqli_fetch_assoc($result))
{
}
This should do it. First you need to connect, then you build your query. If query fails display an error so you know what went wrong. Then build your data array and use it.
$db = mysql_connect("localhost", "mysql_user", "mysql_password");
$sqlStremail = "SELECT `subcheckr`
FROM `login`
WHERE `username` = '".$u."'"; //needs to be concatenated
$result = mysql_query($sqlStremail, $db);
if(!$result) {
echo "query failed:". mysql_error();
exit;
}
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data = $row;
}
echo $data['sponsor'];
echo $data['contact'];
echo $data['script'];
//etc

how to echo a populated php array

I have this code:
<?php
$result_array1 = array();
$sql1 = "SELECT * FROM `test_thing`";
$result1 = mysql_query("$sql1") or die($sql1.mysql_error());
while($row1 = mysql_fetch_array($result1))
{
$result_array1[] = $row1['email'];
}
$sentmail = mail($result_array1,$subject,$message,$header);
?>
My problem is that if I place the mail function inside the loop, the user receives many emails instead of one, and if I place it out of the loop, no email is sent. My aim is to send only 1 email to each user, but that email should containt in it many mixed emails. I have read in other forums that it can be done using arrays. Maybe there is a mistake with the codes.
Any suggestions?
Thanks
try this
<?php
$result_array1 = array();
$sql1 = "SELECT * FROM `test_thing`";
$result1 = mysql_query("$sql1") or die($sql1.mysql_error());
while($row1 = mysql_fetch_array($result1))
{
$result_array1[] = $row1['email'];
}
$email = implode(",",$result_array1); // $email = "one#example.com,two#example.com,three#example.com"
$sentmail = mail($email,$subject,$message,$header);
?>
The first parameter of the mail can be a single email id or email ids separated by commas. Which means you can send the email to multiple users just using one function call.
Just use the following MySQL query:
SELECT DISTINCT email FROM `test_thing`
It will return only unique e-mail addresses from the table. That way you can use the mail() in the loop and not worry about duplicated e-mail addresses.
According to php.net: http://php.net/manual/en/function.mail.php
mail accepts a string for the to address. You could always implode(',', $result_array1)
IMHO $to parameter in mail function just one email support .if you want send to many email, change your $headers and set Bcc;
sample code:
$headers.="Bcc: ";
while($count < $count_recip){
$headers.=$recip[$count].", ";
$count ++;
}
This worked for me:
$result_array1 = array();
$sql1 = "SELECT DISTINCT * FROM `test_thing` GROUP BY `user_id`";
$result1 = mysql_query("$sql1") or die($sql1.mysql_error());
while($row1 = mysql_fetch_array($result1))
{
$result_array1[] = $row1['EmailAddress'];
}
$email = implode(",",$result_array1);
I modified some of the answers together.
There will be no duplicate emails either, atleast there wasn't for me.

MySQL query limit part of query

I have a mysql query:
$result = mysql_query("SELECT * FROM $table WHERE cat = 'category'");
while($row = mysql_fetch_array($result)) {
echo '
<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>
'.$row['title'].'
';
}
This query will generally select between 2 and 5 different rows and display them in a list.
I want the first echoed line to only appear once and the second line should appear between 2 and 5 depending on the data in my db.
I am sure there is a simple way to do this, I've tried GROUP BY mag but this will eliminate the remaining 1-4 pieces of data I wish to display.
Not sure I understand your question, as the following solution seems too simple!
$row = mysql_fetch_array($result);
echo '<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>
'.$row['title'].'';
while ($row = mysql_fetch_array($result)) {
echo ''.$row['title'].'';
}
May be this is a solution to your problem ?
$lines = '';
unset($hgroup);
$result = mysql_query("SELECT * FROM $table WHERE cat = 'category'");
while($row = mysql_fetch_array($result)) {
if (!isset($hgroup)) {
$hgroup = '<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>';
}
$lines += '
'.$row['title'].'
';
}
echo $hgroup.$lines;

PHP/mysql: querying MySQL with an array and getting results in an array

I have an array, $scans. I want to query MySQL with all the values in that array and get my results back in an array. For example, sample data in scans would be:
E1234
E2244
E3654
The MYSQL table PARTS has fields part, size, length, plate, side, type.
I want to end up with $output["E1234"][0] to be the size result for that part, 1 to be length, etc. and I want the array to be sortable by the MYSQL query. (order by SIDE desc, PLATE asc).
Right now, i'm just stepping through the $SCANS array and doing query after query, but I'm not able to then sort all the results properly.
Is this possible? This is what I'm doing now, but obviously since each query returns one row which is then outputted, there's no sortability. I want to be able to perform one query, sort the results within the array, and then output that data after the sort.
foreach ($scans as $currentscan) {
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5);
$query = "SELECT french, length, plate, side, type FROM parts WHERE part = '$partselect' ORDER BY side DESC, plate ASC LIMIT 1";
$result = mysql_query($query);
#echo 'query is '.$query.' <br>';
$error = mysql_error();
$num_rows = mysql_num_rows($result);
if ($num_rows == 0) {
echo 'BAD PART: '.$currentscan.' '.$partselect.' error is '.$error.'<br \>
';
} else {
$row = mysql_fetch_array($result);
print $partselect.' is a '.$row['french'].'/'.$row['length'].' - '.$row['type'].' - '.$row['plate'].'('.$row['side'].')<br \>';
}
};
EDIT: This is the code as it is now following some suggestions here:
$scans = explode("\n",$_POST['scans']);
foreach ($scans as $currentscan) {
if ($currentscan[0] == "E") { //this is a cheap trick to ignore a bad scan inherent in the scanning mechanism
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5);
$tempQuery .= 'part = "'.$partselect.'" OR ';
};
};//end foreach
$tempQuery = substr($tempQuery, 0, -3); //remove last OR (fixed substr to 0,-3 to scrip final OR - stephen)
$tempQuery .= ") ORDER BY side DESC, plate ASC LIMIT 1"; //add on end of query
$query = "SELECT french, length, plate, side, type FROM parts WHERE ".$tempQuery;
$result = mysql_query($query);
echo $result;
while($row = mysql_fetch_array($result)){
print $row['french']." / ".$row['length']; //just doing something pointless to verify data was pulled.
}
result is:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/foo/bar/sort.php on line 35
Line 35 is
while($row = mysql_fetch_array($result)){
FINAL EDIT:
It works.
//DECLARED CONSTANTS//
if (!$_POST) { // Have scans been entered? If not, display the form.
print '
<html>
<body>
Scans:
<form action="index.php" method="post">
<textarea rows="20" cols="6" name="scans" id="scans">
</textarea>
<br />
<input type="submit" value="Submit" />
</body>
</html>
';
} else { //Scans have been entered. Start scan processing logic
//==openDB==//
mysql_connect(SQLSERVER, SQLUSER, SQLPASSWORD) or die("Can not connect to DB server.");
mysql_select_db(DATABASE) or die("Can not connect to Database.");
//==openDB==//
$scans = explode("\n",$_POST['scans']); // Explode posted scans into scans array
foreach ($scans as $currentscan) { // step through each scan
if ($currentscan[0] == "E") { //Cheap check for real part numbers.
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5); // Strip off the extraneous data from the scan
$count{$partselect}++; //Count instances of particular parts. ideally this would be in an array in the form of $count[$partnumber] so I can easily display that data at the end. each part needs to be displayed every time it's scanned.
$tempQuery .= 'part = "'.$partselect.'" OR '; //Starts building query
};
};//end foreach
$tempQuery = substr($tempQuery, 0, -3); //remove last OR
$tempQuery .= ") ORDER BY side DESC, plate ASC"; //add on end of query
$query = "SELECT part, french, length, plate, side, type FROM parts WHERE (".$tempQuery; //Form beginning of query
$result = mysql_query($query);// execute query
while($row = mysql_fetch_array($result)){ // step through results
for ($i = 0; $i < $count{$row['part']}; $i++) { //if a part was scanned $count{$row['part']} times, display it that many times
print $row['part']." ".$row['french']." / ".$row['length']." ".$row['plate']."(".$row['side'].")<br>"; //data parsing goes here. this will be expanded.
};// close for loop
};//close while loop
};//close else
?>
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['name']. " - ". $row['age'];
?>
Courtesy of http://www.tizag.com/mysqlTutorial/mysqlfetcharray.php
You can also if you expect multiple results do:
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
}
?>
Added code for your comment:
foreach ($scans as $currentscan) {
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5);
$tempQuery .= "(part = ".$partselect." OR";
}//end foreach
$tempQuery = substr($tempQuery,-2); //remove last OR
$tempQuery .= ") ORDER BY side DESC, plate ASC LIMIT 1"; //add on end of query
$query = "SELECT french, length, plate, side, type FROM parts WHERE ".$tempQuery;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
//do something with row in result set...
}
Whay you should do is to construct a WHERE clause in PHP, which lets you select all rows that have any of the part numbers. Something like this:
$whereExpr = array();
for ($i = 0; $i < count($scans); $i++) {
$whereExpr[] = "part = \"{$scans[$i]}\"";
}
$whereExpr = implode(" OR ", $whereExpr);
$query = "SELECT * FROM `parts` WHERE $whereExpr ORDER BY <whatev>";
$result = array();
while ($row = mysql_fetch_array) {
$result[ $row['part'] ] = $row;
}
MySQL Fetch Array Function
After looking at your update/edit you could use the IN clause
// Represents your $scans array
$arr = array('Hello','World!','Beautiful','Day!');
foreach ($arr as $currentscan) {
$partselect[] = substr(mysql_real_escape_string($currentscan), 0, 5);
}
$inExpr = implode("','",$partselect);
$query = "SELECT french, length, plate, side, type FROM parts WHERE part IN('$inExpr') ORDER BY side DESC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
print $partselect.' is a '.$row['french'].'/'.$row['length'].' - '.$row['type'].' - '.$row['plate'].'('.$row['side'].')<br \>';
}

Categories