Developing a very simple UPDATE query page for users to change their account password, but have run into a bit of a brick wall with establishing the MySQLi connection (or so it would seem). I'm new to this line of programming and this is my first attempt to perform a dynamic query, so hopefully it's something that one of you can spot easily enough and you'd so kind as to offer some much-needed sage advice.
Here's the page in question: http://www.parochialathleticleague.org/accounts.html
Upon executing the form's PHP script, I was at first receiving nothing but a blank white screen. I scoured through my code and did everything I could think of to diagnose the problem. After eventually adding an "OR die" function to the require command, I am now greeted with this message:
Warning: require(1) [function.require]: failed to open stream: No such file or directory > in /home/pal/public_html/accounts.php on line 10
Fatal error: require() [function.require]: Failed opening required '1'
(include_path='.:/usr/local/php52/pear') in
/home/pal/public_html/accounts.php on line 10
I'm pretty stumped. Here's the script code:
<?php
// Show errors:
ini_set('display_errors', 1);
// Adjust error reporting:
error_reporting(E_ALL);
// Connect to the database:
require ('../mysqli_connect.php') OR die('Error : ' . mysql_error());
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
// Validate the existing password:
if (empty($_POST['pass'])) {
echo "You forgot to enter your existing password.<br>";
$validate = 'false';
} else {
$pass = mysqli_real_escape_string($db, trim($_POST['pass']));
$validate = 'true';
}
// Validate the new password:
if (empty($_POST['new_pass'])) {
echo "You forgot to enter your new password.<br>";
$validate = 'false';
} elseif (empty($_POST['confirm_pass'])) {
echo "You forgot to confirm your new password.<br>";
$validate = 'false';
} elseif ($_POST['new_pass'] != $_POST['confirm_pass']) {
echo "Sorry, your new password was typed incorrectly.<br>";
$validate = 'false';
} else {
$new_pass = mysqli_real_escape_string($db, trim($_POST['new_pass']));
$validate = 'true';
}
// If all conditions are met, process the form:
if ($validate != 'false') {
// Validate the school/password combination from the database:
$q = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass=SHA1('$pass') )";
$r = #mysqli_query($db, $q);
$num = #mysqli_num_rows($r);
if ($num == 1) {
// Get the school_id:
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Perform an UPDATE query to modify the password:
$q = "UPDATE user_schools SET pass=SHA1('$new_pass') WHERE school_id=$row[0]";
$r = #mysqli_query($db, $q);
if (mysqli_affected_rows($db) == 1) {
header("Location: confirm_accounts.html");
} else {
echo "Your password could not be changed due to a system error. Apologies for the inconvenience. If this problem continues, please contact us directly.";
}
}
}
mysqli_close($db);
exit();
?>
Lastly, here's the code from the connection script that it's requiring (with omitted account values, of course):
<?php
// Set the database access information as constants:
DEFINE ('DB_USER', '***');
DEFINE ('DB_PASSWORD', '***');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', '***');
// Make the connection:
$db = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' .mysqli_connect_error() );
// Set the encoding:
mysqli_set_charset($db, 'utf8');
I've been trying for the last couple of hours to troubleshoot this problem on my own. Google couldn't solve it. Looking through archives here couldn't solve it.
Here's what I do know for sure:
The script that it's requiring, mysqli_connect.php, does work on its own. I've tested it extensively to make sure that all of the log-in info is correct.
The script is also definitely in the parent directory that I've requested it from. I've tried moving it to the public directory and calling it from there. Same error message. Tried typing the entire file path. Same message.
Also, most of the script works fine on its own. When I omitted all of the MySQL lines and just left the basic validation code, it ran without a problem and sent me to the confirmation page as requested. It definitely seems to be a problem with making the connection.
Not sure where to go from here. Any assistance would be GREATLY appreciated! Many thanks in advance.
EDIT: #YourCommonSense - Here's the modified script, as per your suggestions. Still getting the blank screen. Am I following your advice incorrectly?
<?php
// Show errors:
ini_set('display_errors', 1);
// Adjust error reporting:
error_reporting(E_ALL);
// Connect to the database:
require ('../mysqli_connect.php');
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
// Validate the existing password:
if (empty($_POST['pass'])) {
echo "You forgot to enter your existing password.<br>";
$validate = 'false';
} else {
$pass = mysqli_real_escape_string($db, trim($_POST['pass']));
$validate = 'true';
}
// Validate the new password:
if (empty($_POST['new_pass'])) {
echo "You forgot to enter your new password.<br>";
$validate = 'false';
} elseif (empty($_POST['confirm_pass'])) {
echo "You forgot to confirm your new password.<br>";
$validate = 'false';
} elseif ($_POST['new_pass'] != $_POST['confirm_pass']) {
echo "Sorry, your new password was typed incorrectly.<br>";
$validate = 'false';
} else {
$new_pass = mysqli_real_escape_string($db, trim($_POST['new_pass']));
$validate = 'true';
}
// If all conditions are met, process the form:
if ($validate != 'false') {
// Validate the school/password combination from the database:
$q = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass=SHA1('$pass') )";
$r = mysqli_query($db, $q);
if (!$r) {
throw new Exception($mysqli->error." [$query]");
}
$num = mysqli_num_rows($r);
if ($num == 1) {
// Get the school_id:
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Perform an UPDATE query to modify the password:
$q = "UPDATE user_schools SET pass=SHA1('$new_pass') WHERE school_id=$row[0]";
$r = mysqli_query($db, $q);
if (!$r) {
throw new Exception($mysqli->error." [$query]");
}
if (mysqli_affected_rows($db) == 1) {
header("Location: confirm_accounts.html");
} else {
echo "Your password could not be changed due to a system error. Apologies for the inconvenience. If this problem continues, please contact us directly.";
}
}
}
mysqli_close($db);
exit();
?>
Two BIGGEST problems with your code and your "solution":
You have # operator all over the place. For which you have -1 vote to your question. # operator is the evil itself. IT is responsible for the blank page you see.
However, the remedy you choose made the things worse. This "OR die" thing is not a magic chant to solve any error reporting problem. And used improperly will cause errors like one you have. For which you have 1 in the error message.
First of all, your include is all right, so, leave it alone.
While to get an error from mysqli, follow these instructions:
Instead of adding "or die" randomly, you need more robust and helpful error reporting solution.
If you are using mysqli_query() all over the application code without encapsulating it into some helper class, trigger_error() is a good way to raise a PHP error, as it will tell you also the file and the line number where error occurred
$res = mysqli_query($mysqli,$query) or trigger_error(mysqli_error($mysqli)."[$query]");
in all your scripts
and since then you will be notified of the reason, why the object weren't created.
(If you're curious of this or syntax, I've explained it here - it also explains why you have (1) in the error message)
However, if you're encapsulating your query into some class, file and line from trigger error will be quite useless as they will point to the call itself, not the application code that caused certain problem. So, when running mysqli commands encapsulated, another way have to be used:
$result = $mysqli->query($sql);
if (!$result) {
throw new Exception($mysqli->error." [$query]");
}
as Exception will provide you with a stack trace, which will lead you the the place from which an erroneous query were called.
Note that you have to be able to see PHP errors in general. On a live site you have to peek into error logs, so, settings have to be
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
while on a local development server it's all right to make errors on screen:
error_reporting(E_ALL);
ini_set('display_errors',1);
and of course you should never ever use error suppression operator (#) in front of your statements.
Related
My .php includes quote.php followed with the rest of the page.
When the connection fails, I see "Fatal error: Uncaught mysqli_sql_exception: ----- include_once('C:\xampp\htdocs...') ----
and the remainder of the page does not load.
What must I do to display an error message, THEN the rest of my page?
Your situation is a rare case when using a try catch is justified.
All you need to do it wrap the include in a try-catch:
try {
require 'quote.php';
} catch(\Throwable $e) {
error_log($e); // for the future inspection
echo "Problem loading this part of page";
}
That's all. The error message will be shown and the rest of the page will be loaded.
But of course this approach should only be used when the content from quote.php is optional. In the every other case there must be no local try-catch but a site-wide error handler.
php / msqli is throwing exceptions. You need to write exception handler code (try { } catch (mysqli_sql_exception $e) { } code in your program to handle errors.
As a quick and sleazy workaroud for the current state of your code you can put this line of code at the top of your page. give this line of code
mysqli_report(MYSQLI_REPORT_OFF):;
This will suppress php exceptions and warnings, and let you rely completely on mysqli_connect_errno() to catch your errors.
Using #O. Jones idea and some nasty GoTO's, this does the job. The warnings and error are still displayed. The rest of the page is able to load now.
<?php
mysqli_report(MYSQLI_REPORT_OFF);
$dbServer = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "project_01";
$conn = mysqli_connect($dbServer, $dbUsername, $dbPassword, $dbName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to the MySQL Database: ";
goto end;
}
$sql = "SELECT * FROM tbl_quotes";
if ($result=mysqli_query($conn,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
$rand = random_int(1,$rowcount);
} else {
echo "No records were found";
goto end;
}
$sql = "SELECT quote, credit FROM tbl_quotes where ID = $rand";
if ($result = mysqli_query($conn, $sql)) {
// Fetch one and one row
while ($row = mysqli_fetch_row($result)) {
printf ("%s" . " - " . "(%s)\n", $row[0], $row[1]);
}
// Free result set
mysqli_free_result($result);
}
end:
?>
Thanks to all who looked.
I'm a beginner of PHP coding which I face this problem and I tried to fix it.
I have search through stackoverflow for answers but it stills no good.
This is my Login form.php file
<form name = 'LoginForm' method = 'POST' action = 'verifyUser.php'>
<br />
E-MAIL: <input type = "Textbox" Name = "App_Email"><br><br>
PASSWORD: <input type = "password" Name = "App_Password"><br><br>
<input type = 'Submit' name = 'Login' value = 'Log in'><br><br>
</form>
This form will goes to verifyUser.php and these are codes
include ('DBconnect.php');
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if($username=='' || $pass=='') {
header("Location:login.php?id=Some fields are empty");
}
$result = mysql_query("SELECT * FROM applicant_acct ");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if ($username==$row['App_Email']) {
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.html?id=$username");
} else {
header("Location:login.php?id=username or your password is incorrect. Please try again");
}
}
}
And final DBconnect.php
<?
$dbc = mysql_connect('localhost','root','root') OR die('Wrong Connection!!!!!!!');
mysql_select_db('onlinerecruitment') OR die ('Cannot connect to DB.');
?>
I really have no idea why it shows "Query Failed: No database selected"
I think the problem is in verifyUser.php but have no idea where.
And another thing, after I logged in how can I generate the text "Welcome - "Username"" and provide them the logout button?
Please help.
Thank you.
Generally you may want to research a graphical user interface such as XAMPP or MySQL workbench until you are more comfortable with Database systems.
Here it seems like most of the improvements can be made in you DBConnect.php file. You are beginning and I can appreciate that. Consider something along the following lines that incorporates additional the security of PDO:: static calls.
<?php
public function _dbconnect($hostpath, $database, $username, $password){
try {
$this->conn = new PDO("mysql:host = {$hostpath};
dbname - {$database};
charset = utf8",
$username,
$password);
} else { exit(); }
?>
If this particular code block doesn't help I would highly recommend that you continue by investigating PDO:: calls.
<?php
include ('DBconnect.php');
if(isset($_POST['Login'])){
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if(empty($username) || empty($pass) || ctype_space($username) || ctype_space($pass)){
header("Location:login.php?error=1");
} else {
$result = mysql_query("SELECT * FROM applicant_acct");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.php?id=$username");
} else {
header("Location:login.php?error=0");
}
}
?>
I have a lot to say about your code.
Use isset function . This function check if something was done.
Check your database details again. Maybe you wrote something
wrong (misclick or something)
Use $_GET['error'] to get errors. I set 1 = for empty characters and 0 for 0 match between database and inputs.
Use sessions for after login message. You can also use Session to handle your errors.
EDIT: I recommend you to start to learn MySQLi or PDO.
I'm new to php. I've been having trouble connecting to and using a data with PHP. I don't really have much information on the issue, maybe I'm using some out of date method, or I did something wrong. I've double checked and looked on this website for information, but I didn't find much. Here's the code below.
The error reads :
Fatal error: Call to a member function query() on boolean in C:\xampp\htdocs\website\Practice\mysqli\pdo.php on line 6
That would mean that there is a problem located near the
$result = $conn->query($sql)or die(mysqli_error());
I entered my username and password correctly. I even created a new username and password just to make sure. I have no other ideas why $conn isn't working, and I would love any thoughts or ideas on the issue!
connection.ini.php
function dbConnect($usertype, $connectiontype = 'pdo') {
$host = 'localhost';
$db = 'student';
if ($usertype == 'read') {
$user = 'user';
$pwd = 'pass';
}
elseif ($usertype == 'write') {
$user = 'root';
$pwd = 'password';
}
else {
exit('Unrecognized connection type');
}
//Connection Code
if ($connectionType ='mysqli') {
return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
}
else {
try {
return new PDO('mysql:host=$host;dbname=$db, $user, $pwd');
}
catch(PDOExecption $e) {
echo 'Cannot connect to database';
exit;
}
}
}
?>
mysqli.php
?php
require_once('connection.inc.php');
$conn = dbConnect('read', 'pdo');
$sql = 'SELECT * FROM guestbook';
$result = $conn->query($sql)or die(mysqli_error());
$numRows = $result->num_rows;
?>
<!DOCTYPE html>
<html>
<p> A total of <?php
echo $numRows;
?>
records were found.</p>
</html>
Any time you get the...
"Fatal error: Call to a member function bind_param() on boolean"
...it is likely because there is an issue with your query. The prepare() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!
First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.
Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
// any additional code you need would go here.
} else {
$error = $mysqli->errno . ' ' . $mysqli->error;
echo $error; // 1054 Unknown column 'foo' in 'field list'
}
If something is wrong you can spit out an error message which takes you directly to the issue. In this case there is no foo column in the table, solving the problem is trivial.
If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.
I have an assignment where I have to make a registration page in php.... I just want to keep things simple so making the form work is all I'm aiming for. I am aware of the vulnerability of sql injections/plaintext, but that's the last of my worries for now since it's a class assignment.
The script below works as far as inserting new users/passwords, but if there's an existing user, the page is blank and doesn't give a warning. I'm looking for help in giving the error "Sorry, this user already exists" shown on the screen (or something).
Thanks :D.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', '////////');
define('DB_USER','/////////');
define('DB_PASSWORD','///////////');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser() { $userName = $_POST['user']; $password = $_POST['pass']; $query = "INSERT INTO UserName (userName,pass) VALUES ('$userName','$password')"; $data = mysql_query ($query)or die(mysql_error()); if($data) { echo "YOUR REGISTRATION IS COMPLETED..."; } } function SignUp() { if(!empty($_POST['user'])) {
$query = mysql_query("SELECT * FROM UserName WHERE userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
if(!$row = mysql_fetch_array($query)))
{ newuser(); }
else { echo "SORRY...YOU ARE ALREADY REGISTERED USER..."; } } } if(isset($_POST['submit'])) { SignUp(); } ?>
First, Its really important check your php_error_log or Add error reporting into the TOP of your file.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
There is an extra closing parenthesis and you are calling an undefined function.
Assuming these are the errors, fix then with:
if(!$row = mysql_fetch_array($query)) {
NewUser();
}
else {
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
Also, consider using mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Hope it helps you.
Thanks to #bcesars for the extra parenthesis fix. I thought there was something odd with the count.
After, I came up with a problem where the "This user already exists" error pops up ONLY if the user and pass matches the same one in the database. If I use a different password, the info is still inserted into the database.
Solution:
Remove
AND pass = '$_POST[pass]'
from
$query = mysql_query("SELECT * FROM UserName WHERE userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
So far it works. I'm still new into this whole database/php thing so thanks for bearing with me ♥
I have created a script for users to invite a friend using a email address, the email address and a randomly generated 10 character string 'inviteCode' is sent to a table called 'referrals'.
The invited person then receives an email with a URL link that contains their email and their unique inviteCode; http://website.com/register.php?email=email&inviteCode=1234567890
When the user clicks on the link the page register.php should then check the URL and if they data is valid in the 'referrals' table. If so then I have an include line to add the register form, if not then they are redirected. The point is nobody can access register.php unless they have been invited and sent a link.
At the moment the page keeps redirecting to index.php;
Register.php script:
<?php
include 'config.php';
if (isset($_GET['email'],$_GET['inviteCode'])) {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
echo 'lol';
}
else
{
echo 'no';
exit;
}
}
else
{
echo 'problem'; //Page not accessible if neither email nor referral entered
}
?>
I replaced the first if statement with:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else
And I receive a blank page with no errors. I believe there may be something wrong with the email and invite code not being set.
Any help on this would be much appreciated (Y) thanks.
You should really be looking at handling the errors first. Try something like this:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='$email' AND inviteCode='$inviteCode'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
include'register-form.php';
} else {
die(header('Location: index.php'));
}
}
Breakdown
The if block checks to see if GET[email] or GET[inviteCode] are not set. if that is the case, kill the app with die() and redirect the user to index.php.
The second change is this line:
if ($query->num_rows > 0) {
That will check to ensure the rows returned are more than 0 (meaning there are actually rows returned.) Because you were just testing the presence of the $query->num_rows before.
Another Note:
Turn on error reporting, it will help you emensly during debugging:
ini_set('display_errors', 1);
error_reporting(E_ALL);
You could alternatively change your sql query to select the COUNT(id) and check if that is greater than 0, but that seems like overkill for what you're trying to do.
Do this to find out if anything is being returned by your query:
Start by making sure that the connection to your database is succeeding:
$mysqli = new Mysqli(/* your connection */);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$email = $mysqli->real_escape_string($_GET['email']);
Add that then let us know the results afterward, also provide specific error messages.
To debug your num_rows, replace this:
$query = $mysqli->query($sql);
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
With this:
$query = $mysqli->query($sql);
$count = $query->num_rows;
print $count;
exit;
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
If it shows 0, I have a suspicion it is because your sql statement needs to be concatenated.
"SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";