send mail based on today date + 3 months against sql date not working - mysql

I' currently working on a scheduled task where task scheduler will run the file daily to pick up expiry date 3 months from now and send email to receipient. But at this point of time, I can't seems to think of the correct syntax to do that. This is what I have right now which is only giving me an error.
<?php
//authentication for database
$hostname = "localhost";
$username = "admin";
$password = "xxxxxx";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("notification",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM tbl_lead WHERE pass_expiry >= DATE(NOW() + INTERVAL 3 MONTHS");
//variable for email message
$emailBody = "";
$headers = 'From: Pass Validity Reminder' . "\r\n" .
'Reply-To: myemail#email.com' . "\r\n" .
'Cc: ccemail#Wemail. com' . "\r\n".
'X-Mailer: PHP/' . phpversion();
$to = "myemail#email.com";
//fetch tha data from the database
while ($row = mysql_fetch_array($result))
{
$subject = $row['company_name']."'s"." work pass is expiry soon";
$emailBody .="Creator: ".$row['rlog_create_user_name']." \n". "Email: ".$row['email']."
\n"."Comment: ".$row['comment']." \n"."Contact: ".$row['contact']." \n";
}
mail($to, $subject, $emailBody, $headers);
echo 'Email sent successfully!';
//close the connection
mysql_close($dbhandle);
?>
However, this error keeps coming up and I'm pretty sure there will be an error message also when there's no match. How can I go about perfecting this script?
( ! ) Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
C:\wamp\www\notification\staff\notify2.php on line 27
Call Stack
# Time Memory Function Location
1 0.0005 681120 {main}( ) ..\notify2.php:0
2 1.0247 689424 mysql_fetch_array ( ) ..\notify2.php:27
( ! ) Notice: Undefined variable: subject in C:\wamp\www\notification\staff\notify2.php on line34
Call Stack
# Time Memory Function Location
1 0.0005 681120 {main}( ) ..\notify2.php:0
I have made the amendment according to #peterm recommendation and the error is gone now. However, now the email still won't send.
I added a check for the email parameters. I had echo out the result before the error message to ensure it pass through the query.
//fetch tha data from the database
while ($row = mysql_fetch_array($result))
{
$subject = $row['company_name']."'s"." work pass is expiry soon";
$emailBody .= "Company: ".$row['company_name']." \n"."Comment: ".$row['comment']."
\n"."Contact: ".$row['contact']." \n";
}
if(mail($to, $subject, $emailBody, $headers)) {
echo 'Email sent successfully!';
} else {
echo $emailBody;
die('Failure: Email was not sent!');
}
The script is suppose to check through every entry in the database and send email for each matching entry. Sorry for the coding in comment, I'm a first time user in stackoverflow and havent been in touch with programming for more than 8 years. Forgetting everything and nv heard of PDO. #peterm.

Your query fails, because SELECT has errors.
Try this one:
SELECT * FROM events WHERE event_date >= DATE(NOW() + INTERVAL 3 MONTH)
You didn't close parenthesis for DATE() function and correct INTERVAL keyword is MONTH.
Now, when a query execution fails mysql_query() returns FALSE instead of a resource. Therefore always check return value before passing $result to mysql_fetch_*:
$result = mysql_query(...);
if (!$result) {
//handle your error
die('The query failed.'); //There are certainly better ways to handle it
}
...
And please, stop using mysql_* functions for new code. They are deprecated. Use prepared statements with either PDO or MySQLi. Here is good PDO tutorial.

Related

How do I change an older version of php work in php7 [duplicate]

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 4 years ago.
How do I make this older version of php work in php7?
I have a mysql database that I use for posting high scores from my games that I create in Construct 2. But now it has stopped working because my host updated to php7 ( at the moment I can choose between php 7.1 - 7.3 )
I have tried for a long time, searching the web, to make it work again, but haven't been able to solve it.
I have 2 php-files: getscores.php and savescores.php
When I try to view getscores.php in a webbrowser ( Chrome ) I get an error:
Fatal error: Uncaught Error: Call to undefined function mysql_query()
...And it's referring to line 18.
I'm sorry but I have almost no knowledge of php and mysql-databases
Thank you so much, in advance, if there's anyone out there who could help. :)
///Soulmachine!
getscores.php
<?php
header('Access-Control-Allow-Origin: *');
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="database"; // Database name
$tbl_name="scores"; // Table name
// Connect to server and select database.
$link = mysqli_connect("$host", "$username", "$password", "$db_name");
// Retrieve data from database
$sql="SELECT * FROM scores ORDER BY score DESC LIMIT 10"; // The 'LIMIT 10' part will only read 10 scores. Feel free to change this value
$result=mysql_query($sql);
// Start looping rows in mysql database.
while($rows=mysqli_fetch_array($result)){
echo $rows['name'] . "|" . $rows['score'] . "|";
// close while loop
}
// close MySQL connection
mysql_close();
?>
savescores.php
<?php
$db = "database";//Your database name
$dbu = "username";//Your database username
$dbp = "password";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysqli_connect($host,$dbu,$dbp,$db);
if(isset($_GET['name']) && isset($_GET['score'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$name = strip_tags(mysql_real_escape_string($_GET['name']));
$score = strip_tags(mysql_real_escape_string($_GET['score']));
$sql = mysqli_query($dblink, "INSERT INTO `$db`.`scores` (`id`,`name`,`score`) VALUES ('','$name','$score');");
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your score was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your score. Please try again later.';
}
}else{
echo 'Your name or score wasnt passed in the request. Make sure you add ? name=NAME_HERE&score=1337 to the tags.';
}
mysqli_close($dblink);//Close off the MySQL connection to save resources.
?>
Replace mysql_query and mysql_close with mysqli_query and mysqli_close respectively.
<?php
header('Access-Control-Allow-Origin: *');
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="database"; // Database name
$tbl_name="scores"; // Table name
// Connect to server and select database.
$link = mysqli_connect("$host", "$username", "$password", "$db_name");
// Retrieve data from database
$sql="SELECT * FROM scores ORDER BY score DESC LIMIT 10"; // The 'LIMIT 10' part will only read 10 scores. Feel free to change this value
$result=mysqli_query($link, $sql);
// Start looping rows in mysql database.
while($rows=mysqli_fetch_array($result)){
echo $rows['name'] . "|" . $rows['score'] . "|";
// close while loop
}
// close MySQL connection
mysqli_close($link);
?>
This should work.

Getting 2 Notice: Undefined Variable errors

The two errors are as below:
Notice: Undefined variable: HawA_Homes in C:\wamp\www\HawA_CIS241\InsertRecord.php on line 48
Notice: Undefined variable: HawA_Homes in C:\wamp\www\HawA_CIS241\InsertRecord.php on line 56
I've checked my names and they appear correct and I am not sure how to proceed now.
Code is as below:
<?php
$hostName = "localhost";
$databaseName = "test";
$userName = "root";
$password = "";
$tableName = "HawA_Homes";
//try to connect report error if cannot
$db = new mysqli($hostName, $userName, $password, $databaseName) or die(" Could not connect:" . mysql_error());
print(" Connection successful to host $hostName <br /> <br />"); //report connection success
//Get data to create a new record
$Address = $_REQUEST["address"];
$DateBuilt = $_REQUEST["dateBuilt"];
$Value = $_REQUEST["value"];
$Size = $_REQUEST["size"];
$Number_of_floors = $_REQUEST["floors"];
$sql = "INSERT INTO $HawA_Homes('Address','DateBuilt','Value','Size','Number_of_floors')VALUES{'$Address','$DateBuilt','$Value','$Size','$Number_of_floors')"; //Create insert query for new record
//try to query dataase / store returned results and report error if not successful
if(!$result =$db->query($sql))
{
//die('There was an error running the query[' .$db->error . ']';
}
print("SQL query $sql successful to database: $HawA_Homes <br /><br />"); //report sql query successful.
?>
You have these notices because the variable $HawA_Homes isn't declared in your code before being used at line 48 and 56. (These are just notices, they are not critical errors, you can avoid displaying them by adding error_reporting(E_ALL & ~E_NOTICE); at the begining of your code, like explained here)
In fact, you used $HawA_Homes instead of $tableName in these lines. Replace them, you won't have notices anymore for these lines.

Fetching data from database in php file

I am trying to fetch data from table. Table contains the data and query is true. Even why following query says $u and $t are not define. While condition becoming false.
I manually checked in database, it was showing results.
$url = "http://paulgraham.com/";
$user_id = "123";
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$result = mysqli_query($con,"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id."");
while ($row = #mysqli_fetch_array($result))
{
echo "hi";
$t = $row['title'];
$u = $row['url'];
}
echo "title is : $t";
echo "url is : $u";
Giving your SQL query :
"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id.""
You can see you are mixing url and userid... Change to :
"SELECT * FROM post_data WHERE userid =".$user_id." and url=".$url.""
Also define your $t and $u variables before your loop in case you have no record.
Next time, try to var_dump your generated query to test it.
If you were able to see the errors the DBMS is reporting back to PHP then you'd probably be able to work out what's wrong with the code.
Before the 'while' loop try...
print mysql_error();
(the obvious reason it's failing is that strings mut be quoted in SQL, and you've got the parameters the wrong way around)

Displaying MYSQL data in a HTML table AFTER a search

I want to thank everyone here for the help I have recieved so far. My next question is a bit more complicated.
So I have a database set up on my server, and I have a form on my website where I am submitting data to my MYSQL database.
After I submit the data, I am having trouble searching for it, displaying possible results, and then making those results HYPERLINKED so that the user can find out more about they are looking for.
My "common.php" script is set up like this:
<?php
$username = "XXX";
$password = "XXX";
$hostname = "XXX"; 
$database = "XXX";
mysql_connect($hostname, $username, $password, $database) or die
("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>��
My "insertdata.php" script is set up like this:
<?php
require("common.php");
// connect with form
$name=$_POST['firstname'];
$lastname=$_POST['lastname'];
$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$various=$_POST['various'];
$other=$_POST['other'];
// insert data into mysql
$query="INSERT INTO datatable
(
firstname,
lastname,
city,
state,
zip,
phone,
email,
various,
other,
)
VALUES
(
'$firstname',
'$lastname',
'$city',
'$state',
'$zip',
'$phone',
'$email',
'$various',
'$other',
)";
$result=mysql_query($query);
// if successfull displays message "Data was successfully inserted into the database".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR... data was not successfully insert into the database";
}
mysql_close();
?>��
From there, I want to make the inserted data searchable.
My problem is, when the search is completed, I want to only display the First Name and Last Name in two separate columns.
From there, I want a link displayed in a third separate column with a link in each row that says "View Record Details."
Finally, when "View Record Details" in clicked, it brings me to the correct record, formatted again in an HTML table.
The closest I have come to a solution is:
<?php
require("common.php");
$query="SELECT * FROM datatable";
$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$firstname=mysql_result($result,$i,"firstame");
$lastname=mysql_result($result,$i,"lastname");
$i++;}
?>
As an additional question, when I use PDO, does that change my HTML?
Switch to PDO. Your code will look something like this:
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$sql = 'SELECT * FROM datatable';
foreach ($conn->query($sql) as $row) {
print $row['firstname'] . "\t";
print $row['lastname'] . "\n";
}
EDIT:
To link back for details add this line after the 2nd print:
print "<a href='somephp.php?idx=" . $row[ 'idx' ] . "'>link here</a>";
You'll need another php file called 'somephp.php':
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$idx = $_REQUEST[ 'idx' ];
$sql = 'SELECT * FROM datatable where idx = ?';
$stmt = $conn->prepare( $sql );
$stmt->bindParam( 1, $idx );
$stmt->execute();
$row = $stmt->fetch();
// now print all the values...
print $row['firstname'] . "\t";
print $row['lastname'] . "\t";
print $row['address'] . "\t";
and so on...
NOTE: This depends on each record having a unique key 'idx'. I don't see this in your values above so you'll have to find a way to incorporate it if you want to use this code.
ALSO: You ask - does this change the HTML and does this handle table formatting - No to both. You do all the HTML formatting via the print statements. All PHP does it output lines to the browser.

Perl DBD error FUNCTION dbName.GLOB does not exist

I am starting to write some Perl scripts for some cron jobs that will query the database and send out reminders about upcoming events. I'm quite new to database access in Perl as most of my work thus far has been on the web end using PHP. Anyway, the first query is working fine to generate a temporary output file and then I'm reading back in that output file to loop thru the results querying to find the specific events for the users discovered in the first query.
The problem that I am running into now is getting the following error:
./remind.pl
DBD::mysql::st execute failed: FUNCTION dbName.GLOB does not exist at ./remind.pl line 41.
SQL Error: FUNCTION dbName.GLOB does not exist
This is my Perl code
$host = 'localhost';
$database = 'dbName';
$user = 'user';
$password = 'password';
use POSIX qw(strftime);
use List::MoreUtils qw(uniq);
use Mail::Sendmail;
use DBI;
$dt = strftime("%Y%m%d%H%M%S", localtime(time));
$List30 = "../tmp/queries/30DayUserList.$dt";
open my $UserList30Day, ">> $List30" or die "Can't create tmp file: $!";
$dbh = DBI->connect('dbi:mysql:dbName',$user,$password) or die "Connection error: $DBI::errstr\n";
$sql = "SELECT DISTINCT user FROM shows WHERE initial_date BETWEEN CURDATE() AND CURDATE() + INTERVAL 30 DAY";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while (#jeweler = $sth->fetchrow_array()) {
print $UserList30Day "$user[0]\n";
}
close $UserList30Day;
open my $UserIDList, "< $List30" or die "Can't open temp file: $List30";
while ($id = $UserIDList) { # Read in User ID from temp file as $id
# Query for show information for next 30 days
my $sql = "SELECT shows.initial_date, shows.initial_time, shows.hostess_key, hostess.hostess_fname, hostess.hostess_lname, hostess.primary_phone, hostess.address1, hostess.address2, hostess.city, hostess.zipcode, hostess.state
FROM shows, hostess
WHERE shows.user = $id
AND initial_date BETWEEN CURDATE() AND CURDATE() + INTERVAL 30 DAY
AND shows.hostess_key = hostess.hostess_key";
my $sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
# Iterate thru query results to create output data
while (#row = $sth->fetchrow_array()) {
$content = "Reminder: You have a show for $row[3] $row[4] coming up on $row[0] at $row[1].\n";
$content .= "Location: $row[6] \n";
if ($row[7] != '') {
$content .= " " . $row[7] . "\n";
}
$content .= " $row[8], $row[10] $row[9] \n";
$content .= "Phone: $row[5] \n";
}
%mail = (To => 'email',
From => 'email',
Subject => 'Just another test',
Message => $content
);
# sendmail(%mail) or die $Mail::Sendmail::error;
print %mail;
}
close $UserList30Day;
Thanks in advance for any assistance.
while ($id = $UserIDList) {
should be
while ($id = <$UserIDList>) {
chomp;