sending an email in PHP with information taken from database - php

I want to pull an email from the database as the recipient. If I replace the line "SELECT student_user_email FROM students";' with an actual email address I get the desired outcome. However it would be handier to pull a particular email address from the 'students' table. Below is the current code. Wondering if anyone can help?
mail('"SELECT student_user_email FROM students";','Sample Form',$msg, 'From: johnsmith#gmail.com');

First, use mysqli or PDO because the mysql_ functions are depricated. The documentation has very useful information to get started with it.
mysqli: http://php.net/manual/en/book.mysqli.php
pdo: http://us3.php.net/pdo
mail: http://us3.php.net/manual/en/function.mail.php
This is what you need to do to connect to your database (from the php documentation: http://www.php.net/manual/en/mysqli.quickstart.connections.php)
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Once connected you can query the database:
$result = $mysqli->query("SELECT student_user_email FROM students");
while ($row = $result->fetch_object()) {
if (isset($row->student_user_email)) {
mail($row->student_user_email,'Sample Form',$msg, 'johnsmith#gmail.com');
}
}

You can't send email to a multiple recipients in this way. Because query return array list so you must be looping and send email one by one recipients by this following way,
Try this will work:
<?php
$con = mysqli_connect("localhost", "uname", "password");
if (!$con){
die('Could not connect: ' . mysqli_error());
}
$db_selected = mysqli_select_db("database",$con);
$sql = "SELECT student_user_email FROM students";
$result = mysqli_query($sql,$con);
while ($row_data = mysqli_fetch_array($result)) {
// Then you will set your variables for the e-mail using the data
// from the array.
$from = 'you#yoursite.com';
$to = $row_data['email']; // The column where your e-mail was stored.
$subject = 'Sample Form';
$msg = 'Hello world!';
mail($to, $subject, $msg, $from);
}
?>

Related

Failed to query daabaseNo database selected

i am getting error no database is selected can anybody correct the code.
I am trying to learn php and mysql. So i tried making a database using
phpmyadmin and connect it with my php. Here is a simple example where I try to see if the database is working.
<?php
//Get values passe from form in donateform.html.
$link;
$Name = $_POST['Name'];
$Mobile = $_POST['Mobile'];
$Email = $_POST['Email'];
$Donating =isset($_POST['Donating']);
$Address = isset($_POST['Address']);
//To prevent mysql injection
$Name = stripcslashes($Name);
$Mobile = stripcslashes($Mobile);
$Email = stripcslashes($Email);
$Donating = stripcslashes($Donating);
$Address = stripcslashes($Address);
//connect to the server and select database.
$link=mysqli_connect("localhost", "gooddeeds", "");
mysqli_select_db($link,"donaters");
$Name = mysqli_real_escape_string($link,$Name);
$Mobile = mysqli_real_escape_string($link,$Mobile);
$Email = mysqli_real_escape_string($link,$Email);
$Donating = mysqli_real_escape_string($link,$Donating);
$Address = mysqli_real_escape_string($link,$Address);
//Query the database for user
$result =mysqli_query($link,"INSERT INTO donaters (Name, Mobile, Email, Donating, Address) VALUES ('$Name', '$Mobile', '$Email', '$Donating', '$Address')")
or die("Failed to query daabase".mysqli_error($link));
if(mysqli_query($result)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. ".mysqli_error($link);
}
?>
and i get
Database query failed::: No database selected
which means this part of code
//connect to the server and select database.
$link=mysqli_connect("localhost", "gooddeeds", "");
mysqli_select_db($link,"donaters");
is not working (i put a different number of these ":" in each if. Any help would be appreciated! Thank you!
You can try with following as databasename.tablename (gooddeeds.donaters)
INSERT INTO gooddeeds.donaters (Name, Mobile, Email, Donating, Address) VALUES ('$Name', '$Mobile', '$Email', '$Donating', '$Address')
This is by the first example in the php documentation. Try the the conditional to check connection.
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}

Converting from mysql to mysqli and getting Fatal error: Cannot use object of type mysqli as array

I am working on converting some PHP code from mysql to mysqli. I have created an error and am unable to understand how to fix it. Any suggestions would be greatly appreciated.
The code looks like this:
<?php
include ("admin/includes/connect.php");
$query = "select * from posts order by 1 DESC LIMIT 0,5";
$run = mysqli_query($conn["___mysqli_ston"], $query);
while ($row=mysqli_fetch_array($run)){
$post_id = $row['post_id'];
$title = $row['post_title'];
$image = $row['post_image'];
?>
The error produced is: Fatal error: Cannot use object of type mysqli as array
The error is being called out on this line:
$run = mysqli_query($conn["___mysqli_ston"], $query);
In the line above $conn is a variable from the database connect file which has this code:
<?php
// Stored the db login credentials in separate file.
require("db_info.php");
// Supressing automated warnings which could give out clues to database user name, etc.
mysqli_report(MYSQLI_REPORT_STRICT);
// Try to open a connection to a MySQL server and catch any failure with a controlled error message.
try {
$conn=mysqli_connect ('localhost', $username, $password) or die ("$dberror1");
} catch (Exception $e ) {
echo "$dberror1";
//echo "message: " . $e->message; // Not used for live production site.
exit;
}
// Try to Set the active MySQL databaseand catch any failure with a controlled error message.
try {
$db_selected = mysqli_select_db($conn, $database) or die ("$dberror2");
} catch (Exception $e ) {
echo "$dberror2";
//echo "message: " . $e->message; // Not used for live production site.
exit;
// We want to stop supressing automated warnings after the database connection is completed.
mysqli_report(MYSQLI_REPORT_OFF);
}
?>
This line
$run = mysqli_query($conn["___mysqli_ston"], $query);
should be
$run = mysqli_query($conn, $query);
If you're migrating to mysqli, you should really read these docs at least.
The proper way to use a mysqli connection:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}
?>
you should also consider utilizing mysqli's prepared statements

Body of the mail in PHP

I can able to display some HTML contents in the body of the mail in PHP using the below code
$body = file_get_contents('yourfile.html');
But I wanted to retrieve and display the user password in the body of the mail, stored in database.
Please give some suggestions.
Hi Heres my way of doing it. hope it helps :)
To Select the Password from Database:
// connect to the mysql server
$mysqli = new mysqli(MYSQL_SERVER, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->conect_errno . ')'
. $mysqli->connect_error);
}
mysqli_set_charset($mysqli, 'utf8');
// query the password (please dont store passwords plaintext! :)
// fetch an assoc array of the selected row afterwards
$result = $mysqli->query("SELECT password FROM users WHERE user='j.doe'");
$row = $result->fetch_array(MYSQLI_ASSOC);
// retrive password and map it to a variable you can use in your mail body
$userPassword = $row['password'];

PHP How to shoot an email with an attched table?

I use i-page as a hosting company. I have a mySQL database. How can i shoot an email with an attached table? Let's say i have connected to my database:
$link = mysql_connect('www.....com', 'login', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('rates', $link);
// Now how do i SELECT table1??
// Do i create a variable $table = SELECT...
// Then how to attach it to an email and send the email?

Sending emails to multiple recipients (PHP, My SQL)

Hi I am new to this and only have a basic understanding on PHP so any help would be most welcome. Basically I am trying to send an email via PHP that can have multiple recipients. The content also needs to display a list of users following certain criteria. I have got the script to look at the database and send an email however it only sends it to one person and only lists one person in the content. Please could someone advise on how to change that to email / display to multiple recipients. I know that there should be at least three people it is sent to.
Any help / pointers would be most welcome. Thank you.
<?php
session_start();
require_once('../config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(database_name);
if(!$db) {
die("Unable to select database");
}
$result = mysql_query("SELECT username FROM users WHERE user_type='admin'");
while($result_email = mysql_fetch_array($result))
$to = $result_email['username'];
$result2 = mysql_query("SELECT * FROM users
WHERE ticked='1' AND NOT user_type='super'");
while($result2 = mysql_fetch_array($result2))
$body = $result2['fname'] . " " . $result2['lname'] . " , " . $result2['username'];
mail ($to, 'Subject', $body);
?>
You can do that. They just need to be comma separated.
$to = "email#email.com, email2#email2.com";
Reference: http://php.net/manual/en/function.mail.php
Also, your code is a little confusing the way you have pasted it. But if you are loading all the emails in a while loop. Then you want to send it after the while. For example:
You want it to be:
//create an empty $to string
$to = '';
//add all the emails
while($emails as $email)
{
$to .= $email . ',';
}
//remove the last comma
rtrim($to, ",");
//send away
mail($to, $subject, $message);
your code is wrong. you would have error if you used it. you need to use implode to add comma between the emails. check your php. i corrected but you have to use while statement right. you have multiple mysql query for one job. also you should not use mysql_query. use PDO instead...
you should use it like this
<?php
while($row = mysql_fetch_array($result2))
{
$addresses[] = $row['username'];
}
$to = implode(", ", $addresses);
?>
with your code
<?php
session_start();
require_once('../config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(database_name);
if(!$db) {
die("Unable to select database");
}
$result = mysql_query("SELECT username FROM users WHERE user_type='admin'");
while($row = mysql_fetch_array($result2))
{
$addresses[] = $row['username'];
}
$to = implode(", ", $addresses);
$result2 = mysql_query("SELECT * FROM users
WHERE ticked='1' AND NOT user_type='super'");
$body = mysql_fetch_array($result2);
$body = $result2['fname'] . " " . $result2['lname'] . " , " . $result2['username'];
mail ($to, 'Subject', $body);
?>
You are overwriting the value of $to repeatedly with the statement $to = $result_email['username'];. You should make a comma-separated list instead. But for goodness' sake,
Consider setting the addresses as BCC, and set TO to something that does not matter, e.g. noreply#[yourdomain] to hide the recipients' addresses from each other.
Use DB-access that is not deprecated: PDO
Your call to mail() is not in a loop, so it will only send one e-mail.
And your while loop where you're setting $to is simply overwriting the previous value each time the loop iterates.
So in the end $to will be set to the last username the first query returns. And your $body will be the body you want for the last row your second query returns.

Categories