php login system problem - mysql

$con = mysql_connect("xx","xx","xx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ban", $con);
$pass=$_POST["password"];-------------> line 10
$mail=$_POST["email"];----------------->line 11
$result31 = mysql_query
("SELECT * FROM `users` WHERE email = '$mail'AND password='$pass'");
$login_check = mysql_num_rows($result31);
echo $login_check;
mysql_close($con)
this is a part of a login system, but it is not working correctly
error i got was:-
Notice: Use of undefined constant password - assumed 'password' in D:\wamp\www\phpadder.php on line 10
Notice: Use of undefined constant email - assumed 'email' in D:\wamp\www\phpadder.php on line 11
Warning: mysql_num_rows() expects parameter 1 to be resource, string given in D:\wamp\www\phpadder.php on line 17
what's wrong with it?

On your error it says you forgot the $ symbole before your password variable,
but also
Your query should be
("SELECT * FROM `users` WHERE email = '$mail' AND password='$pass'");
you forgot to add a space between mail and AND
also consider escaping your values first before using in the query
$sql = "SELECT * FROM `users` WHERE email = '%s' AND password='%s'";
$sql = sprintf($sql,mysql_real_escape_string($mail),mysql_real_escape_string($pass));
now you can query
$result = mysql_query($sql);

The error you are seeing is because your are probably using $_POST[password] and $_POST[email] somewhere.
However, these are just notices, and if you read them well you will see they will have the same effect as using quotes around them (which you really should!)
But your query is also not correct, this will create a valid query:
$result31 = mysql_query
("SELECT * FROMusersWHERE email = '$mail' AND password='$pass'");
Note the extra space between '$mail' and AND.

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.

SQL error text giving me a different value that the actual value

This is the line of code that is causing the error:
$result = $mysqli->query("SELECT * FROM 'accounts'.'users' WHERE email='$email' AND hash='$hash' AND active='0'") or die($mysqli->error);
and this is the error that shows:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''accounts'.'users' WHERE email='testemail#email.com' AND hash='76dc611d6eba' at line 1
However, if I print the value of hash I get this "76dc611d6ebaafc66cc0879c71b5db5c" the value that I want to search with and the value that is stored in the database. I am not sure if it is just being shortened for the error message of if something else is happening.
Try changing from ' (apostrophe) to ` (backtick) or simply removed the single quotes from db/table name, so your query looks like this:
SELECT * FROM `accounts`.`users` WHERE email='$email' AND hash='$hash' AND active='0'
Try removing quotes around database and table name
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$result = $mysqli->query("SELECT * FROM accounts.users WHERE email='$email' AND hash='$hash' AND active='0'") or die($mysqli->error);

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.

Update MySQL within Perl loop failing (fetchrow_array)

I've created a Perl script which is meant to loop through an array (a shortlist of customers who meet certain criteria), execute an external command using system() , then update a field within each row once the operation has completed.
It works on the first record (ie external command executes, customer record updates), however when it gets to the second record I receive this error:
DBD::mysql::st fetchrow_array failed: fetch() without execute() at customer_update.pl
Through some googling I added the $sth->finish(); command, however whether I include it or not (either inside the loop as shown, or straight afterward) I still get the same error.
Can anyone shed any light for me as to what I am doing wrong here?
Here's an extract:
# PERL MYSQL CONNECT()
$dbh = DBI->connect('dbi:mysql:signups', $user, $pw)
or die "Connection Error: $DBI::errstr\n";
# DEFINE A MySQL QUERY
$myquery = "SELECT * FROM accounts WHERE field3 = false";
$sth = $dbh->prepare($myquery);
# EXECUTE THE QUERY
$sth->execute
or die "SQL Error: $DBI::errstr\n";
#records = $sth->rows;
print "Amount of new customers: #records\n\n";
while ( my ($field1, $field2, $field3) = $sth->fetchrow_array() ) {
#execute external command via system();
$update_customer_status = "UPDATE accounts SET field3=true WHERE id=$id";
$sth = $dbh->prepare($update_customer_status);
$sth->execute
or die "SQL Error: $DBI::errstr\n";
print "Customer record modified & MySQL updated accordingly\n\n";
$sth->finish();
}
Building a SQL statement with variables and then prepare()ing it defeats the purpose of the prepare. You should build the SQL statement with a placeholder ? instead of $id, prepare() it, and then execute($id) it. As it is, you are leaving yourself open to SQL injection attacks.
Also, it seems that you are not using the warnings and strict pragmas. These two lines should be at the top of every program you write:
use warnings;
use strict;
They will save you much heartache and frustration in the future.
In your loop, you overwrite the handle over from which you are fetching. Use a different variable. (Changing $sth = ...; to my $sth = ...; will do.) While we're at it, let's move the prepare out of the loop.
my $sth_get = $dbh->prepare("SELECT * FROM accounts WHERE field3 = false");
my $sth_upd = $dbh->prepare("UPDATE accounts SET field3=true WHERE id = ?");
$sth_get->execute();
while ( my ($field1, $field2, $field3) = $sth_get->fetchrow_array() ) {
...
$sth_upd->execute($id);
}
You are stomping on your $sth variable when you execute this line ...
$sth = $dbh->prepare($update_customer_status);
Why not save off the result of $sth->fetchrow_array() to an array variable.
Something like ...
my #select_results_AoA = $sth->fetchrow_array();
... and then iterate over the array ...
for my #row ( #select_resilts_AoA ) {
... instead of ...
while ( my ($field1, $field2, $field3) = $sth->fetchrow_array() ) {

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.