Unusual Fatal Error with required files - php

Im trying to design a registration page with a drop down box in it. This requires 2 database connections one to send the data to the database upon hitting the registration button and the other to pull information from the database to populate the drop down box. I had this script working flawless until a few days ago when i uploaded a file that has no relation to the other files other than a require statement to get the config.inc.php (for db connection and error handling purposes.) This file is used on almost in all my scripts and works fine on all but a few scripts in my website. After this file was uploaded the section of my registration sript populates the drop down box nolonger works.
Below is the sript in question (I have omited the datavalidation and most of the html sections i can re-add them if needed.)
<?php
require_once('includes/config.inc.php');
$page_title = 'Register';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require_once(MYSQL);
$trimmed = array_map('trim', $_POST);
$fn = $ln = $usr = $pw = $bd = $gs = $bs = FALSE;
//DATA VALIDATION
//END DATA VALIDATION
if($fn && $ln && $usr && $e && $pw && $bd && $gs && $bs) {
$q = "SELECT user_id FROM Users WHERE email='$e'";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br/>MySQL Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) == 0) {
$a = md5(uniqid(rand(), true));
$q = "INSERT INTO Users (first_name, last_name, user_name, email, password1, birthdate, gamespy_id, base, active, registration_date) VALUES ('$fn', '$ln', '$usr', '$e', SHA1('$pw'), '$bd', '$gs', '$bs', '$a', NOW() )";
$r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n <br/>MySQL Error:" . mysqli_error($dbc));
if (mysqli_affected_rows($dbc) == 1){
$body = "Thank you for registering with Gateway Aviation. To activate your account, please click on this link:\n\n";
$body .= BASE_URL . 'activate.php?x=' . urlencode($e) . "&y=$a";
mail($trimmed['email'],'Registration Confirmation', $body, 'From: noreply#virtual-aviation.org');
echo '<h3> Thank you for registering! A confirmation email has been sent to your address. Please click on the link in that email in order to activeate your accout.</h3>';
exit();
} else {
echo '<p class="error>You could not be registered due to a system error. We apologize for any inconvenience.</p>';
}
} else {
echo '<p class="error"> That email has already been registered. If you have forgotten your password, use the link to reset it.</p>';
}
} else {
echo '<p class="error">Please try again</p>';
}
}
?>
<td><input type='text' name='gamespyid' value='<?php if(isset($trimmed['gamespyid'])) echo $trimmed['gamespyid'];?>'/></td>
</tr>
<td>Base:</td>
<td><select name="base" size="1">
<option>
Select One
</option>
<?php
require_once(MYSQL);
$q = "SELECT airport_id, CONCAT_WS(' ', airport_code,' - ' airport_name) FROM airports ORDER BY airport_code ASC";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) > 0) {
while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
echo "<option value=\"$row[0]\"";
if (isset($_POST['existing']) && ($_POST['existing'] == $row[0]) ) echo 'selected="selected"'; echo ">$row[1]</option>\n";
}
} else {
echo '<option>Please a new airport first.</option>';
}
mysqli_free_result($result);
?>
</select></td>
</table>
<input type='submit' name='submit' value='Register'/>
</form>
</body>
</html>
Im also getting this error in my error log
[20-Aug-2012 03:09:25] PHP Fatal error: Cannot redeclare my_error_handler() (previously declared in /home5/virtua15/public_html/gatewayaviation/includes/config.inc.php:36) in /home5/virtua15/public_html/gatewayaviation/includes/config.inc.php on line 56

you should have
require_once('includes/config.inc.php');
require_once(MYSQL);
but why do you require the config and MYSQL twice? Once it's enough for the entire script, it will work for any IF statements if you start with them.

Use
require_once('includes/config.inc.php');
at the top and remove the second require('includes/config.inc.php'); instance.
Keep the connection open and only close it at the end of the script. Rather dispose of results once you have pulled the data from the database using mysqli_free_result($result);

Related

PHP code inserts into sql db with text box inputs but not with select options (dropdowns)

Through hours of research and looking through code in questions submitted on this site, I was finally able to get the select options (dropdowns) to pull data from my database tables into the dropdown lists on my html form.
However, my issue is that when the fields on the form were inputs they inserted the new information into the database just fine. Unfortunately, now that I've implemented the dropdown lists as part of the form, none of the information from the form inserts into the database anymore. Clicking on the 'submit' button returns the response that it was successful, but when I check the table in the database, the new information is not there.
I'm sorry I haven't been able to figure this piece of functionality out by myself. I noticed my last question received negative feedback, so I'm leary to even submit this one, but I really need some help.
Will you please look through the following code and let me know what I'm missing or have coded incorrectly? I just need to know what I need to do to make the selected values from the dropdown lists insert into the 'dvd' table and 'categoryname' and 'genretype' fields, respectively.
<?php
session_start();
//include the header
include ('../main/header.php');
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {
require_once ('../../../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize error array.
// Check for a first name.
if (empty($_POST['title'])) {
$errors[] = 'You forgot to enter a title.';
} else {
$title = mysqli_real_escape_string($dbc, $_POST['title']);
}
// Check for a category.
if (empty($_POST['numavail'])) {
$errors[] = 'You forgot to enter quantity purchased.';
} else {
$numavail = mysqli_real_escape_string($dbc, $_POST['numavail']);
}
// Check for a category.
if (empty($_POST['categoryname'])) {
$errors[] = 'You forgot to enter a category.';
} else {
$categoryname = mysqli_real_escape_string($dbc, $_POST['categoryname']);
}
// Check for a genre.
if (empty($_POST['genretype'])) {
$errors[] = 'You forgot to enter a genre.';
} else {
$genretype = mysqli_real_escape_string($dbc, $_POST['genretype']);
}
if (empty($errors)) { // If everything's OK.
// Add the movie to the database.
// Check for existing record.
$query = "SELECT id FROM dvd WHERE title='$title'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
if ($result) { // If it ran OK.
echo "<p><b>Success! The new movie has been added.</b></p>";
echo ('<p><div style="margin-top:30px;">');
echo ('<span style="float:left;">');
echo ('<FORM METHOD="LINK" ACTION="../dvd/index.php"><INPUT TYPE="submit" VALUE="Back to DVDs" STYLE="margin:0px 15px 0px 0px;"></form></span></div></p>');
echo ('<br style="clear:both;"></br>');
exit();
} else { // If it did not run OK.
$errors[] = 'The movie could not be added due to a system error. We apologize for any inconvenience.'; // Public message.
$errors[] = mysqli_error($dbc); // MySQL error message.
}
} else { // Title is already taken.
$errors[] = 'The movie title entered already exists.';
}
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} else { // Form has not been submitted.
$errors = NULL;
} // End of the main Submit conditional.
// Begin the page now.
if (!empty($errors)) { // Print any error messages.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo "$msg<br />";
}
echo '</p>';
echo '<p style="color:red; font-weight:bold;"><em>Please try again.</em></p></br>';
}
// Create the form.
?>
<h1>Add a Movie</h1>
<h2>Please complete all of the fields below:</h2>
<form action="../dvd/add.php" method="post">
<p>Title: <input type="text" name="title" size="15" maxlength="15" value="<?php echo $_POST['title']; ?>"></p>
<p>Quantity Purchased: <input type="text" name="numavail" size="15" maxlength="30" value="<?php echo $_POST['numavail']; ?>"></p>
<p>
<?php
include ('../../../mysqli_connect.php'); // Connect to the db.
$ddlquery = "SELECT categoryname FROM category ORDER BY categoryname ASC";
$ddlresult = mysqli_query($dbc, $ddlquery) or die("Bad SQL: $ddlquery");
echo 'Category: <select name="categoryname" size="1">';
while($ddlrow=mysqli_fetch_array($ddlresult, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow['categoryname']."'>" . $ddlrow['categoryname'] . "</option>";
}
echo "</select>";
?>
<p>
<?php
$ddlquery2 = "SELECT genretype FROM genre ORDER BY genretype ASC";
$ddlresult2 = mysqli_query($dbc, $ddlquery2) or die("Bad SQL: $ddlquery");
echo 'Genre: <select name="genretype" size="1">';
while($ddlrow2=mysqli_fetch_array($ddlresult2, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow2['genretype']."'>" . $ddlrow2['genretype'] . "</option>";
}
echo "</select>";
?>
<p>
<input type="submit" name="submit" value="Submit">
<input type=reset value=Reset>
<input type="hidden" name="submitted" value="TRUE"></p>
</form>
<?php
// Include footer.php
include("../../includes/footer.php");
?>
You forgot to actually run the insert into database
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
$result = mysqli_query($dbc, $query); // <---- ADD HERE
if ($result) { // If it ran OK.
....

PHP Error - What does my error I am getting mean?

I am getting this error after clicking the delete link on the view_users.php page. I think the error is on the delete_users.php page but when I use the data files version that you can download from his site I still get the same error.
This is the error:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /var/www/PHP and MySQL for Dynamic Web Sites/Chapter 9/delete_user.php on line 38
<?php # Script 10.2 - delete_user.php
// This page is for deleting a user record.
// This page is accessed through view_users.php.
$page_title = 'Delete a User';
include ('includes/header.html');
echo '<h1>Delete a User</h1>';
// Check for a valid user ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
include ('includes/footer.html');
exit();
}
require ('mysqli_connect.php');
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['sure'] == 'Yes') { // Delete the record.
// Make the query:
$q = "DELETE FROM users WHERE user_id=$id LIMIT 1";
$r = #mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// Print a message:
echo '<p>The user has been deleted.</p>';
} else { // If the query did not run OK.
echo '<p class="error">The user could not be deleted due to a system error.</p>'; // Public message.
echo '<p>' . mysqli_error($dbc) . '<br />Query: ' . $q . '</p>'; // Debugging message.
}
} else { // No confirmation of deletion.
echo '<p>The user has NOT been deleted.</p>';
}
} else { // Show the form.
// Retrieve the user's information:
$q = "SELECT CONCAT(last_name, ', ', first_name) FROM users WHERE user_id=$id";
$r = #mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid user ID, show the form.
// Get the user's information:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Display the record being deleted:
echo "<h3>Name: $row[0]</h3>
Are you sure you want to delete this user?";
// Create the form:
echo '<form action="delete_user.php" method="post">
<input type="radio" name="sure" value="Yes" /> Yes
<input type="radio" name="sure" value="No" checked="checked" /> No
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="id" value="' . $id . '" />
</form>';
} else { // Not a valid user ID.
echo '<p class="error">This page has been accessed in error. </p>';
}
} // End of the main submission conditional.
mysqli_close($dbc);
include ('includes/footer.html');
?>
// mysqli_query failed and returned false instead of returning a mysqli_result
$r = #mysqli_query ($dbc, $q);
//on the line below you pass $r which is false because the query failed
if (mysqli_num_rows($r) == 1) {
You should check to see if $r is false and figure out what went wrong
if($r===false)
{
echo mysqli_error($dbc) ;
}
Try checking if there's anything wrong with your database connection. So see if $dbc is throwing any errors, it may be causing mysqli_query()some problems. For debugging sakes remove the error control operator in front of mysqli_query().
Also, see if the query that you're trying to run (SELECT CONCAT(last_name, ', ', first_name) FROM users WHERE user_id=$id) throws any errors. As a quick tip, don't use string interpolation for your queries, try to bind the variables to a prepared statement as parameters.

PHP/mySQLi update values where user exists

We'll get to the point...
I have a simple form (2 of them) that relies off the previous filled out.
The intention of these forms are to sign, post to db, validate email. After the user validates their email their permission will change to be able to see the next form.
These forms work great, and everything is functional in exception to this last bit.
I am having difficulty with the form applying the values to the db table when there is existing user.
What I would like to do is only have it update the keys for that user where users session-ed API key =$API AND form_ica_initials is NULL in the roster table. If it does then will INSERT INTO
Here is what I have cleaned up. (originally wrote for the first phase of the forms to be filled out, trying to tweak to work for last half of forms)
if (empty($_POST['initials'])) { $error[] = 'You must enter your initials in every box below.'; }
else { $initials = $_POST['initials']; }
$API = $_SESSION['API'];
if (empty($error)) {
$query_verify_form = "SELECT * FROM roster WHERE API ='$API'";
$result_verify_form = mysqli_query($dbc, $query_verify_form);
if (!$result_verify_form) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_form) == 0) {
$form_icaauth = md5(uniqid(rand(), true));
error_reporting(E_ALL);
$query_insert_user = "UPDATE `roster`
(
`fullname`, `form_ica_initials`, `form_icaauth`,`form_ica_ip`
)
VALUES (
'$fullname', '$initials', '$form_icaauth','$DOCSIGNEDBYIP'
)
";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) {
...
echo '<br><center><div class="success">...</div>';
}
else {
echo '<center><div class="error">...</div></center>';
}
}
else {
echo '<center><div class="warning" >...</div></center>';
}
}
else {
echo '<center><div class="info"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div></center>';
}
mysqli_close($dbc); //Close the DB Connection
}
If I change the if (mysqli_num_rows($result_verify_form) == 0) { to ==1 It will post the values to the table by creating a new record, and not update the existing users fields as specified. However, by doing that it will circumvent the errors that I have structured.
I know my way around PHP a bit... but having difficultly with this one
I was able to get it to work with the following.
if (empty($error)) {
$query_verify_form = "SELECT * FROM roster WHERE API='$API' AND form_ica_initials IS NULL";
$result_verify_form = mysqli_query($dbc, $query_verify_form);
if (mysqli_num_rows($result_verify_form) == 1) {
$form_icaauth = md5(uniqid(rand(), true));
error_reporting(E_ALL);
$query_insert_user = "UPDATE roster SET fullname='$fullname', form_ica_initials='$initials', API='$API', form_icaauth='$form_icaauth', form_ica_ip='$DOCSIGNEDBYIP'";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo '<center><div class="error">Query Failed </div></center>';
}
First I had to change if (mysqli_num_rows($result_verify_form) == 1) from 0 to 1 to return Yes we've found that record.
I then had to change the INSERT INTO ... VALUES to UPDATE ... SET. I added also added AND form_ica_initials IS NULL to validate that the user hasn't completed this form yet. IF they have, then we'd prompt with a message to check their email. If they havent then we'd run the UPDATE

When using NetBeans to debug PHP script to modify table records, 'affected_rows' will change from 1 to -1

I am testing a simple PHP-MySQL script, and it's to delete one record from the table. The strange thing is in this block of code:
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['sure'] == 'Yes') { // Delete the record.
// Make the query:
$q = "DELETE FROM users WHERE user_id=$id LIMIT 1";
$r = #mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
When I use NetBeans to debug this script, after the record is deleted($r = #mysqli_query ($dbc, $q) is executed), the affected_rows = 1 in the variable section of NetBeans, which is correct. But then after I press F7 to step into and 'if (mysqli_affected_rows($dbc) == 1)' is executed, affected_rows suddenly becomes -1, and the program logic jumps to the error reporting branch.
If I don't debug and just run the script, the Deletion is totally OK. What's the possible cause?
Here's the whole script:
<?php # Script 10.2 - delete_user.php
// This page is for deleting a user record.
// This page is accessed through view_users.php.
$page_title = 'Delete a User';
include ('includes/header.html');
echo '<h1>Delete a User</h1>';
// Check for a valid user ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
include ('includes/footer.html');
exit();
}
require ('./mysqli_connect.php');
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['sure'] == 'Yes') { // Delete the record.
// Make the query:
$q = "DELETE FROM users WHERE user_id=$id LIMIT 1";
$r = #mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// Print a message:
echo '<p>The user has been deleted.</p>';
} else { // If the query did not run OK.
echo '<p class="error">The user could not be deleted due to a system error.</p>'; // Public message.
echo '<p>' . mysqli_error($dbc) . '<br />Query: ' . $q . '</p>'; // Debugging message.
}
} else { // No confirmation of deletion.
echo '<p>The user has NOT been deleted.</p>';
}
} else { // Show the form, to confirm that this user should be deleted.
// Retrieve the user's information:
$q = "SELECT CONCAT(last_name, ', ', first_name) FROM users WHERE user_id=$id";
$r = #mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid user ID, show the form. (Just 1 result as user_id is PK)
// Get the user's information:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Display the record being deleted:
echo "<h3>Name: $row[0]</h3>
Are you sure you want to delete this user?";
// Create the form:
echo '<form action="delete_user.php" method="post">
<input type="radio" name="sure" value="Yes" /> Yes
<input type="radio" name="sure" value="No" checked="checked" /> No
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="id" value="' . $id . '" />
</form>';
} else { // Not a valid user ID.
echo '<p class="error">This page has been accessed in error.</p>';
}
} // End of the main submission conditional.
mysqli_close($dbc);
include ('includes/footer.html');
?>
Another problem is that after running the script, there are many lines of warnings:
Warning: main(): Couldn't fetch mysqli in C:\xampp\htdocs\phpmysql4_working\delete_user.php on line 75
Warning: main(): Couldn't fetch mysqli in C:\xampp\htdocs\phpmysql4_working\includes\footer.html on line 11
Call Stack
# Time Memory Function Location
1 0.1000 146128 {main}( ) ..\delete_user.php:0
2 249.5054 187032 include( 'C:\xampp\htdocs\phpmysql4_working\includes\footer.html' ) ..\delete_user.php:75
But MySQL was actually been accessed successfully. The footer.html is:
<!-- End of the page-specific content. --></div>
<div id="footer">
<p>Copyright © Plain and Simple 2007 |
Designed by edg3.co.uk |
Sponsored by Open Designs |
Valid CSS & XHTML</p>
</div>
</body>
</html>
I investigated, and found that this is not something that Xdebug does wrong, but the MySQLi extension itself. I filed a bug report for PHP at https://bugs.php.net/bug.php?id=67348

validation php not working?

The following is the email verification code for my site.
The verification url sent to the user's email is as follows:
http://www.mywebsite.com/valid.php?confr=2774405&userid=2
Extra notes :
1) key is a column in my database which gets a random value on registration.
2) if $verify == 1 and password_in_db=== user_entered_password, then login takes place in the login page.
<?php
include 'connect.php';
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$_GET['userid']'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1") {
echo "Link Expired . Go to our login page :";
} else {
if (isset($_GET["confr"]) && isset($_GET["userid"])) {
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2) {
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$_GET["userid"]' ;");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
} else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Code for connect.php
<?php
mysql_connect("host", "username", "pass"); //connects to the server
mysql_select_db("database_name"); //selects the database
?>
The problem is that it is giving me a blank screen .
i believe the error lies in the sql
when ever i use a "WHERE" statement i always define as a variable, try this
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
also, you have a semi colon in the insert sql
Try this.......
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
while ($details = mysql_fetch_assoc($query)){
$verify = $details['verify'];
$confirm2 = $details['key'];
}
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Note: insert statement has no where - as long as you dont use "insert into select..."
http://dev.mysql.com/doc/refman/5.1/de/insert.html

Categories