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

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.

Related

If there is no $_POST present after a URL, how can I prevent (nothing) from getting passed into a MySQL query, and causing an error?

I have a Delete.php page that deletes records based on their ID.
When there is an ID, i.e., Delete.php?id=3610, all is well, and it functions as expected.
If I just go to "Delete.php" and that's it - no ID, it generates:
"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 '' at line 1"
From the little I understand, it is doing this because I am trying to pass a nonexistent variable into my query.
I have been trying to put if (empty($_POST['id'])) { } in different places, which removes the error, but breaks something else.
Here is my code:
<?php
require_once 'functions.php';
$conn = mysqli_connect("localhost", "user", "pass",'db');
writeHead("Delete Track");
if (isset($_POST['delete'])) {
$trkid = $_POST['trkid'];
$query = "DELETE FROM track WHERE TrackID=$trkid";
mysqli_query($conn, $query) or die(mysqli_error($conn));
if (mysqli_affected_rows($conn)>0) {
header("Location: Display.php?action=deleted&id=$trkid&status=deleted");
exit();
}
echo "<p class='error'>Unable to update record</p>";
} else {
if (!isset($_GET['id'])) {
echo "<p class='error'>No Track ID provided.<br><a href='Display.php'>Return to display page.</a><p>";
}
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}
?>
<p>Track Information:</p>
<p><?php echo "<b>ID: $trkid <br>Title: $Name</b>"; ?></p>
<form method="post" action="Comp3Delete.php">
<p>
<input type="hidden" name="trkid" value="<?php echo $trkid; ?>">
<input type="submit" name="delete" class="btn" value="Confirm Delete">
</p>
</form>
<p>Return to Track Table Display</p>
<?php writeFoot(); ?>
Your post code is fine. it's the GET code that's wrong:
if (!isset($_GET['id'])) {
^^^^^^^^--check if the parameter exists
}
$trkid=$_GET['id'];
^---try to use the parameter ANYWAYS, even if it doesn't exist.
$trkid=$_GET['id']; has no condition so it runs even when no id is passed which generates the error. Your code should go like this:
if(isset($_GET['id'])){
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}

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

Unusual Fatal Error with required files

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);

Using PHP to add numeric values to two MySQL database rows

I have a site in which logged in users can accumulate points which they can later buy with via a shopping cart. The page below is an admin php feature in which an Admin can give points to an individual user (one user at a time for now).
There are three tables involved with this script:
users: contains the users details
tally_point: stores all of the points transactions, both incoming and ordering
reward_points: stores the total amount of points that the user has
The script retrieves the users’ details via a drop down menu and adds the points to the tally point table ok but....
<?php # add-points-ind.php
// This is the main page for the site.
// Include the configuration file for error management and such.
require_once ('./includes/config.inc.php');
// Set the page title and include the HTML header.
$page_title = 'Add Points to User';
include ('includes/header_admin_user.html');
// If no dealer_code variable exists, redirect the user.
if (!isset($_SESSION['admin_int_id'])) {
// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
?>
<h1>Add Points to User</h1>
<div id="maincontent_inner">
<div id="maincontent_inner2">
<?php //add-points-ind.php
// This page allows the admin to add points to an individual user
require_once ('mydatabase.php'); // Connect to the database.
if (isset($_POST['submitted'])) { // Check if the form has been submitted.
// Check if points were submitted through the form.
if (is_numeric($_POST['tally_points_in'])) {
$p = (float) $_POST['tally_points_in'];
} else {
$p = FALSE;
echo '<p><font color="red">Please enter the pointås!</font></p>';
}
// Validate the User has been selected
if ($_POST['selected_user'] == 'new') {
// If it's a new categories, add the categories to the database.
$query = 'INSERT INTO tally_points (users_id) VALUES (';
// Check for a last_name.
if (!empty($_POST['users_id'])) {
$query .= "'" . escape_data($_POST['users_id']) . "')";
$result = mysql_query ($query); // Run the query.
$a = mysql_insert_id(); // Get the categories ID.
} else { // No last name value.
$a = FALSE;
echo '<p><font color="red">Please enter the Dealers name!</font></p>';
}
} elseif ( ($_POST['selected_user'] == 'existing') && ($_POST['existing'] > 0))
{ // Existing categories.
$a = (int) $_POST['existing'];
} else { // No categories selected.
$a = FALSE;
echo '<p><font color="red">Please select a registered Dealer!</font></p>';
}
if ($p && $a) { // If everything's OK.
// Add the print to the database.
$query = "INSERT INTO tally_point (users_id, tally_points_in, order_id, total, tally_points_entry_date) VALUES ('$a', '$p', '0', '0', NOW())";
if ($result = mysql_query ($query))
{
// Worked.
echo '<p>The reward product has been added.</p><br />Go back<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
} else {
// If the query did not run OK.
echo '<p><font color="red">Your submission could not be
processed due to a system error.</font></p>';
}
} else { // Failed a test.
echo '<p><font color="red">Please click "back" and try again.</font></p>';
}
} else { // Display the form.
?>
<form enctype="multipart/form-data" action="add-points-ind.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="524288" />
<fieldset>
<legend>Add Points Individually:</legend>
<p><b>Select User:</b></p>
<p>
<select name="existing"><option>Select One</option>
<?php // Retrieve all the users details and add to the pull-down menu.
$query = "SELECT users_id, users_sale_id, users_first_name, users_surname FROM users ORDER BY users_surname ASC";
$result = #mysql_query ($query);
while ($row = #mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo "<option value=\"{$row['users_id']}\">{$row['users_sale_id']}: {$row['users_first_name']} {$row['users_surname']} </option>\n";
}
#mysql_close($dbc); // Close the database connection.
?>
</select></p>
<span class="extras"><input type="radio" name="selected_user" value="existing" /> Please confirm this is the correct user</span>
<p><b>Points:</b> <br />
<input type="text" name="tally_points_in" size="10" maxlength="10" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden"name="submitted" value="TRUE" />
</form>
<?php
} // End of main conditional.
?>
<br class="clearboth" />
End text
</div>
<?php // Include the HTML footer file.
include ('includes/footer_admin_user.html');
?>
... Im having trouble with getting the new points added to the points total field (reward_user_points) in the reward_points table, I have some code below but Im not sure where I am supposed to put it, if anyone has any suggestions please let me know.
<?php
$query = "SELECT reward_user_points FROM reward_points WHERE users_id = $a";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$TotalPoints = $row['reward_user_points'];
if (#mysql_affected_rows($dbc) == 1) { // Whohoo!
$new_credit = $TotalPoints + $p;
$query = "UPDATE reward_points SET reward_user_points ='$new_credit' WHERE users_id = $a";
$result = #mysql_query($query);
}
?>
Ok, I have to say that I don't understand very well what your trouble is. You say you're having trouble with getting the new points added to the points total field, but could you be a little more specific? Is there any error message returned by php or mysql?

How can I make my form input not return any results when it is inputted with an empty query?

I want my form input not to act upon an empty search.
I don't want it to even go to the results page and show an error message.
SO
how can I have it so nothing happens when clicking the submit/pressing enter OR pressing space bar then enter?
Can this be done with javascript?
HTML:
<form action="search.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
PHP:
<?php
$conn = mysql_connect("", "", "")
or die (mysql_error());
mysql_select_db("testable");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
$term = addcslashes($term,'%_');
$term = "%" . $_POST["term"] . "%";
if (!mysql_select_db("weezycouk_641290_db2")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
**if (isset($_POST['term']) && ($_POST['term'] !== '')) {
$term = $_POST['term'];
$safe_term = mysql_real_escape_string($term);
$sql = "SELECT FName,LName,Phone
FROM testable
WHERE FName LIKE '%". mysql_real_escape_string($term) ."%'";
$result = mysql_query($sql);
}**
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br><br><div class="data1">';
echo htmlentities($row["FName"]);
echo '</div><br><div class="data2">';
echo htmlentities($row["LName"]);
echo '</div><br><div class="data3">';
echo htmlentities($row["Phone"]);
echo '</div>';
}
mysql_free_result($result);
?>
Preventing the form from being submitted via JS is a quick fix, but you still need to handle the possibility that someone could STILL submit a blank search:
if (isset($_POST['term']) && ($_POST['term'] !== '')) {
$term = $_POST['term'];
$safe_term = mysql_real_escape_string($term);
$sql = "...."
blah blah blah
}
note the use of mysql_real_escape_string(). It is THE safe method for strings in mysql queries. addslashes is a hideously broken piece of crap and should NEVER be used for SQL injection prevention.
You can check the length in JS and abort is it's blank
Yes, you can do that using javascript.
Add a javascript function to handle on click event of submit button.
<input type="submit" name="submit" value="Submit" onclick="submitForm(event)" />
Inside that javascript function, check whether textbox is empty or not
function submitForm(event){
var val = document.getElementsByName('term')[0].value;
if (val==null || val.trim()==""){
//document.getElementsByTagName('form')[0].submit();
event.preventDefault();
return false;
}
else {
return true;
}
}
If empty, prevent default event and return false => prevent submission
if not empty, return true => submit the form.

Categories