Getting 2 Notice: Undefined Variable errors - undefined

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.

Related

Database login incorrect

I'm having some trouble with some software that I'm tweaking. During my install script I can type my database username, database name, localhost, etc and once I click next it is suppose to connect to the database and start the install. However when I click next I have shown this error:
Database Login Incorrect: config.php
Here is my config.php file:
<?php
// Mysql Settings
$mysqli_host = "";
$mysqli_login = "";
$mysqli_pass = "";
$mysqli_database = "";
$db_prefix = "";
$_dbConn = mysqli_connect($mysqli_host, $mysqli_login, $mysqli_pass)
or die ('Database Login Incorrect: config.php');
mysqli_select_db($mysqli_database, $_dbConn)
or die ('Unable to select the database: config.php');
?>
Although the database name and username are correct and have proper permissions. I can show the install file but it is over 2k lines and didn't want to post all of that :p
Thanks for your time!
Edit:
After using Geo V L's fix, I now have the error of "have you run install.php yet?". This is located in my structure.php file:
// Include functions...
include "scripts/php/functions.php";
// get board theme
$query2 = "select THEME from {$db_prefix}settings";
$result2 = mysqli_query($query2) or die("Have you run install.php yet?");
$theme = mysqli_result($result2, 0);
In this code snippent $_dbConn will be the first parameter for mysqli_select_db
<?php
// Mysql Settings
$mysqli_host = "";
$mysqli_login = "";
$mysqli_pass = "";
$mysqli_database = "";
$db_prefix = "";
$_dbConn = mysqli_connect($mysqli_host, $mysqli_login, $mysqli_pass)
or die ('Database Login Incorrect: config.php');
mysqli_select_db( $_dbConn,$mysqli_database)
or die ('Unable to select the database: config.php');
?>
Or you can directly add databasename on mysqli connect string like the following
<?php
// Create connection
$conn = mysqli_connect($mysqli_host, $mysqli_login, $mysqli_pass, $mysqli_database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>

Infinite Loading When Trying to Connect Into MySQL

I'm having a problem connecting to mysql database in XAMPP. It always takes time to load this segment of php code. What might be the problem?
<?php
session_start();
//redirect function
function returnheader($location){
$returnheader = header("location: $location");
return $returnheader;
}
$connection = mysqli_connect("localhost:85","root","") OR die(mysqli_error());
$db_select = mysqli_select_db("pts",$connection) OR die(mysqli_error());
$errors = array();
if(isset($_POST["iebugaround"])){
//lets fetch posted details
$uname = trim(htmlentities($_POST['uname']));
$passw = trim(htmlentities($_POST['psw']));
//check username is present
if(empty($uname)){
//let echo error message
$errors[] = "Please input a username";
}
//check password was present
if(empty($passw)){
//let echo error message
$errors[] = "Please input a password";
}
if(!$errors){
//encrypt the password
$passw = sha1($passw);
$salt = md5("userlogin");
$pepper = "ptsbtr";
$passencrypt = $salt . $passw . $pepper;
//find out if user and password are present
$query = "SELECT * FROM users WHERE username='".mysqli_real_escape_string($uname)."' AND password='".mysqli_real_escape_string($passencrypt)."'";
$result = mysqli_query($query) OR die(mysqli_error());
$result_num = mysqli_num_rows($result);
if($result_num > 0){
while($row = mysqli_fetch_array($result)){
$idsess = stripslashes($row["id"]);
$firstnamesess = stripslashes($row["firstname"]);
$username = stripslashes($row["username"]);
$_SESSION["SESS_USERID"] = $idsess;
$_SESSION["SESS_USERFIRSTNAME"] = $firstnamesess;
$_SESSION["SESS_USERNAME"] = $username;
setcookie("userloggedin", $username);
setcookie("userloggedin", $username, time()+43200); // expires in 1 hour
//success lets login to page
returnheader("users-area.php");
}
} else {
//tell there is no username etc
$errors[] = "Your username or password are incorrect";
}
}
} else {
$uname = "";
}
?>
And this is the error after loading it for minutes.
Warning: mysql_connect(): MySQL server has gone away in C:\xampp\htdocs\peopletrackingsystem\login.php on line 10
Warning: mysql_connect(): Error while reading greeting packet. PID=6940 in C:\xampp\htdocs\peopletrackingsystem\login.php on line 10
Warning: mysql_connect(): MySQL server has gone away in C:\xampp\htdocs\peopletrackingsystem\login.php on line 10
Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\peopletrackingsystem\login.php on line 10
(backstory: my Apache is also having a problem with localhost/127.0.0.1. It only appears blank page every time I try to access it with just localhost. So I always put the port every time I try to access it. I already removed all unnecessary port in hosts file. I already change the listen port of the httpd.conf and the Server name too with the port in it)
You can't add the port in "localhost:85", try it like this:
$connection = mysqli_connect("localhost","root","") OR die(mysqli_error());

Warning: mysql_select_db() expects parameter 2 to be resource,

<?php
$servername = "localhost";
$username = "root";
$password = "Rachel";
$db = "hairdressingapointments";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected Sussessfully";
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
$sql = "SELECT `ApointmentDate`, `ApointmentTime` FROM `apointments` WHERE `staff_id`=1 && `quantity`>0";
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
echo $sql;
mysql_close();
?>
spent hours trying to figure this out and im guessing its something so simple. getting back the following error:
Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\wamp2\www\hairdressingapointments\TeresaApointments.php on line 15 which is,
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
You already connected to the database using
mysqli_connect(...);
So, you do not need
mysql_select_db(....);
Also change the query to this
$sql = "SELECT ApointmentDate, ApointmentTime FROM apointments WHERE staff_id=1 AND quantity>0";
If you use SQLWorkbench or SQLYog or some other tool, you can enter your SQL and make sure it is valid before adding it to your script.
Also, make sure the table name is really
apointments
and not
appointments
I got this information from php.net - mysqli_connect

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

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.

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;