I am copying a youtube video tutorial for private messaging. The rest of the tutorial works fine, but as soon as I add this function to my site, my entire site goes blank and nothing is shown? No errors or anything, just a white screen? Have I done something wrong here? Here is the function:
<?php
function fetch_user_ids($usernames){
foreach ($usernames as &$name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
$names = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$names[$row['username']] = $row['userid'];
}
return $names;
}
?>
Here is the script to send the information:
<?php
if (isset($_POST['to'], $_POST['subject'], $_POST['body'])){
$errors = array();
if (empty($_POST['to'])){
$errors[] = 'You must enter atleast one name.';
}else if (preg_match('#^[a-z, ]+$#i', $_POST['to']) === 0){
$errors[] = 'The list of names you gave does not look valid.';
}else{
$usernames = explode(',', $_POST['to']);
foreach ($usernames as &$name){
$name = trim($name);
}
$user_ids = fetch_user_ids($usernames);
if (count($user_ids) !== count($usernames)){
$errors[] = 'The following users could not be found: ' . implode(', ', array_diff($usernames, array_keys($user_ids)));
}
}
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty';
}
if (empty($_POST['body'])){
$errors[] = 'You body must have some text!';
}
if (empty($errors)){
//Send message
}
}
if (isset($errors)){
if (empty($errors)){
echo '<div class="msg success">Your message has been sent ! return</div>';
}else{
foreach ($errors as $error){
echo '<div class="msg error">', $error, '</div>';
}
}
}
?>
<form action="" method="POST">
<div>
<label for="to">To</label>
<input type="text" name="to" id="to" />
</div>
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" />
</div>
<div>
<textarea name="body" rows="10" cols="110"></textarea>
</div>
<div>
<input type="submit" value="send" />
</div>
</form>
If I take away the "function" part, I can print the data, so it must be something to do with the function element?
I would suggest changing the !== to != and seeeing if that works, it could be interpreting it has a number and not as a bool
Make it simpler. Inside foreach, get rid of &$name and replace it with $name. Also check if your database is returning nothing.
foreach ($usernames as $name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
// Check if the query itself is failing or not here:
if(!$result) die("Failed to perform query");
$names = array();
// Check if the database is returning any rows or not:
print_r(mysql_num_rows($result));
while($row = mysql_fetch_assoc($result)){
$names[$row['username']] = $row['userid'];
}
return $names;
Related
I'm working in a update file using php and mysql but the update function doesn't work. I wrote the code using an example and modified according to the requirements. The file does work and doesn't really drop any error but it doesn't change anything in the database. It is suppose to update a book database.
Code:
<?php
$page_title = 'Add Books';
include ('bookincludes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize an error array.
if (empty($_POST['title'])) {
$errors[] = 'Please add title.';
} else {
$e = mysqli_real_escape_string($dbc, trim($_POST['title']));
}
if (empty($_POST['author'])) {
$errors[] = 'Please add the name of the author.';
} else {
$p = mysqli_real_escape_string($dbc, trim($_POST['author']));
}
if (!empty($_POST['isbn1'])) {
if ($_POST['isbn1'] != $_POST['isbn2']) {
$errors[] = 'ISBN number does not match.';
} else {
$np = mysqli_real_escape_string($dbc, trim($_POST['isbn1']));
}
} else {
$errors[] = 'You need to enter ISBN number.';
}
if (empty($errors)) { // If everything's OK.
$q = "SELECT ISBN FROM Books WHERE (Title='$e' AND Author ='$p')";
$r = #mysqli_query($dbc, $q);
$num = #mysqli_num_rows($r);
if ($num == 1) { // Match was made.
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Make the UPDATE query:
$q = "UPDATE Books SET ISBN='$np' WHERE ISBN = $row[0] ";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// Print a message.
echo '<h1>Thank you!</h1>
<p>Thank you, Book has been added or modified</p><p><br /></p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">System error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
}
mysqli_close($dbc); // Close the database connection.
// Include the footer and quit the script (to not show the form).
include ('includes/footer.html');
exit();
} else {
echo '<h1>Error!</h1>
<p class="error">ISBN number is incorrect.</p>';
}
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p><p><br /></p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} // End of the main Submit conditional.
?>
<h1>Update</h1>
<form action="Bupdate.php" method="post">
<p>ISBN number: <input type="text" name="isbn1" size="20" maxlength="60" value="<?php if (isset($_POST['isbn1'])) echo $_POST['isbn1']; ?>" /> </p>
<p>Confirm ISBN: <input type="text" name="isbn2" size="20" maxlength="60" value="<?php if (isset($_POST['isbn2'])) echo $_POST['isbn2']; ?>" /> </p>
<p>Author: <input type="text" name="author" size="20" maxlength="60" value="<?php if (isset($_POST['author'])) echo $_POST['author']; ?>" /></p>
<p>Title: <input type="text"" name="title" size="20" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; ?>" /></p>
<p>Year: <input type="text"" name="year" size="20" maxlength="60" value="<?php if (isset($_POST['year'])) echo $_POST['year']; ?>" /></p>
<p><input type="submit" name="submit" value="Update" /></p>
</form>
<?php include ('bookincludes/footer.html'); ?>
This is what If I try to change the ISBN got:
System error. We apologize for any inconvenience.
Query: UPDATE Books SET ISBN='978-1782175910' WHERE ISBN =
978-1782175919
If I tried to update the ISBN or the year but I get the message above.
How can I fix this?
The query requires that text values are wrapped in quotes like this
$q = "UPDATE Books SET ISBN='$np' WHERE ISBN = '$row[0]'";
Although I would look for a tutorial that uses parameterised and prepared queries rather than string concatenated queries to avoid SQL Injection
And any tutorial that suggests using the # error silencing prefix should tell you the author has no idea what they are doing and should be avoided like the plague.
you seem to be missing single quotes on your where clause
UPDATE Books SET ISBN='978-1782175910' WHERE ISBN = 978-1782175919
should be
UPDATE Books SET ISBN='978-1782175910' WHERE ISBN = '978-1782175919'
The script is about editing data retrieved from database. It works fine (it edits the data) but the errors array is displayed immediately when the script runs. So i get all there errors: forgotten title, body, date.
For testing purposes i omit the title for example and click submit i get only the you forgot to enter your title
<?php
$page_title = 'Edit a Joke';
include ('includes/header.html');
echo '<h1>Edit a Joke</h1>';
// Check for a valid Joke ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_jokes.php
$id = $_GET['id'];
}
else { // No valid ID, kill the script.
echo '<p>This page has been accessed in error.</p>';
exit();
}
require ('mysqli_connect.php');
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$errors = array();
// Check for a title
if (empty($_GET['title'])) {
$errors[] = 'You forgot to enter title.';
} else {
$tit = mysqli_real_escape_string($dbc, ($_GET['title']));
}
// Check for body:
if (empty($_GET['body'])) {
$errors[] = 'You forgot to enter body.';
} else {
$bod = mysqli_real_escape_string($dbc, ($_GET['body']));
}
// Check for date:
if (empty($_GET['date'])) {
$errors[] = 'You forgot to enter date.';
} else {
$dat = mysqli_real_escape_string($dbc, ($_GET['date']));
}
if (empty($errors)) // If everything's OK.
{
// Make the query:
$q = "UPDATE joke SET title='$tit', body='$bod', date='$dat' WHERE joke_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 joke has been edited.</p>';
} else { // If it did not run OK.
echo '<p class>The joke could not be edited. Sorry</p>'; // Public message.
}
}
else { // Report the errors.
echo '<p>The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p>';
}// End of if (empty($errors)) IF.
}// End of submit conditional.
// Always show the form...
// Retrieve the joke information:
$q = "SELECT title, body, date FROM joke WHERE joke_id=$id";
$r = #mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid joke ID, show the form.
// Get the joke's information:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Create the form:
echo '<form action="edit_joke.php" method="GET">
<p> Title: <input type="text" name="title" value="' . $row[0] . '" /></p>
<p> Body: <input type="text" style="height: 100" size="100" name="body" value="' . $row[1] . '" /> </p>
<p> Date: <input type="date" name="date" value="' . $row[2] . '" /> </p>
<p> <input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</form>';
} else { // Not a valid joke ID.
echo '<p>This page has been accessed in error.</p>';
}
mysqli_close($dbc);
?>
Change at the beginning:
if (isset($_GET['test'])) {
$errors = array();
// Check for a title
....
}
// Always show the form...
And add in your <form:
<input type="hidden" name="test" value="1">
I’m trying to make a form that will check if the NRIC that is keyed exists in the database before it will insert the value into the database. However, I can’t seem to make it warn the user that there is already a duplicate entry. How do I go about doing it ?
Form:
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php find_selected_page(); ?>
<?php
if (isset($_POST['submit'])) {
// Process the form
//validations
$required_fields = array("first_name", "last_name", "nric", "address", "birthdate", "phone", "doctor");
validate_presences($required_fields);
$fields_with_max_lengths = array("phone" => 8);
validate_max_lengths($fields_with_max_lengths);
if( verify_nric($_POST['nric'])) {
$errors[] = 'This NRIC exists already.';
}
if( !isValid( 'phone', $_POST['phone'] ) ) {
$errors[] = 'Please enter a valid phone number';
}
if( !isValid( 'nric', $_POST['nric'] ) ) {
$errors[] = 'Please enter a valid nric number';
}
if (empty($errors)) {
// perform Create
$name = mysql_prep($_POST["name"]);
$age = (int) $_POST["age"];
$nric = mysql_prep($_POST["nric"]);
$birthdate = mysql_prep($_POST["birthdate"]);
$allergy = mysql_prep($_POST["medical_allergy"]);
$history = mysql_prep($_POST["medical_history"]);
$phone = (int)$_POST["phone"];
$address = mysql_prep($_POST["address"]);
$doctor = mysql_prep($_POST["doctor"]);
//escape content
// 2. Perform database query
$query = "INSERT INTO patients (";
$query .= " name, age, nric, birthdate, medical_allergies, medical_history,
phone, address, doctor_assigned";
$query .= ") VALUES (";
$query .= " '{$name}', {$age}, '{$nric}', '{$birthdate}',
'{$allergy}', '{$history}', {$phone}, '{$address}', '{$doctor}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result ) {
// Success
$_SESSION["message"] = "Record Created.";
}else {
// Failure
$_SESSION["message"] = "Record creation failed.";
}
}
} else {
// This is probably a GET request
} // End: If(isset($_POST['submit']))
?>
<?php $layout_context = "admin"; ?>
<link rel="stylesheet" type="text/css" href="css/dashboard-icons.css" />
<link rel="stylesheet" type="text/css" href="css/dashboard-component.css" />
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Create Patient</h2>
<form action="create_patient.php" method="post">
<p>First Name:
<input type="text" name="first_name" value="" />
</p>
<p>Last Name:
<input type="text" name="last_name" value="" />
</p>
<p> NRIC/ Foreign ID/ Passport:
<input type="text" name="nric" value="" />
</p>
<p>Date Of Birth:<br />
<input type="text" name="birthdate" value="" />
</p>
<p>Contact Number:
<input type="text" name="phone" value="" />
</p>
<p>Address:
<textarea name="address" rows="1" cols="40" align="right"></textarea>
</p>
<p>Dentist Assigned:<br />
<input type="text" name="doctor" value="" />
</p>
<div id="limit">
<p>Medical Allergies:<br />
<textarea name="medical_allergy" rows="15" cols="40"></textarea>
</div>
<p>Medical History:<br />
<textarea name="medical_history" rows="15" cols="40"></textarea>
<input type="submit" name="submit" value="submit" />
</form>
<br />
Cancel
</div>
Validation Function:
function verify_nric($nric){
global $connection;
$query = "SELECT nric ";
$query .= "FROM patients ";
$query .= "ORDER BY nric ASC";
$nric_set = mysqli_query($connection, $query);
confirm_query($nric_set);
if ($nric == $nric_set) {
return $nric_set;
}
}
function isValid( $what, $data ) {
switch( $what ) {
// validate a phone number
case 'phone':
$pattern = "/^[0-9-+()\s]+$/";
break;
case 'nric':
$pattern = "/^(A-Z)?[0-9]{7}[A-Z]$/i";
break;
default:
return false;
break;
}
return preg_match($pattern, $data) ? true : false;
}
confirm_query
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed: ".
mysqli_connect_error() .
" (" . mysqli_connect_errno(). ")"
);
}
}
Not sure what confirm_query() does but you could change your function to:
function verify_nric($nric){
global $connection;
$query = "SELECT nric ";
$query .= "FROM patients ";
$query .= "WHERE nric='".mysqli_real_escape_string($connection,$nric)."'"; //changed your query a little here
$nric_set = mysqli_query($connection, $query);
confirm_query($nric_set); // you haven't mentioned what this function does so I'm going to leave it that way.
$nric_found=false; //Added
if(mysqli_num_rows($nric_set)>0){ //
$nric_found=true; //These
} //
return $nric_found; //Lines
}
Now to explain where you went wrong:
Your select query returned all the nric but you weren't fetching the
values and checking against $nric. You need to use
mysqli_fetch_array() to get the values from the resultset
$nric_set
$nric == $nric_set is invalid because you are
comparing a resultset($nric_set) with a value $nric
The error i got was:
Notice: Undefined index: visible in C:\xampp\htdocs\introducingphp\includes\validation_function.php on line 22
It should not happen since i already instantiated all the variables including visible
Validation_function.php
<?php
$errors = array();
function fieldname_as_text($fieldname) {
$fieldname = str_replace("_", " ", $fieldname);
$fieldname = ucfirst($fieldname);
return $fieldname;
}
// * presence
// use trim() so empty spaces don't count
// use === to avoid false positives
// empty() would consider "0" to be empty
function has_presence($value) {
return isset($value) && $value !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
// * string length
// max length
function has_max_length($value, $max) {
return strlen($value) <= $max;
}
function validate_max_lengths($fields_with_max_lengths) {
global $errors;
// Expects an assoc. array
foreach($fields_with_max_lengths as $field => $max) {
$value = trim($_POST[$field]);
if (!has_max_length($value, $max)) {
$errors[$field] = fieldname_as_text($field) . " is too long";
}
}
}
// * inclusion in a set
function has_inclusion_in($value, $set) {
return in_array($value, $set);
}
?>
new_page.php (the page that has the one-page submit form that does validation)
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php find_selected_page(); ?>
<?php
// Can't add a new page unless there is a subject as a parent
if (!$current_subject) {
// subject ID was missing or invalid or
//subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit'])) {
// Process the form
//validations
$required_fields = array("menu_name", "position", "visible",
"content");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 60);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors)) {
// perform Create
//add the subject_id
$subject_id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
//escape content
$content = mysql_prep($_POST["content"]);
// 2. Perform database query
$query .= "INSERT INTO pages (";
$query .= " subject_id, menu_name, position, visible,
content";
$query .= ") VALUES (";
$query .= " {$subject_id}, '{$menu_name}', {$position},
{$visible}, '{$content}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result ) {
// Success
$_SESSION["message"] = "Page Created.";
redirect_to("manage_content.php?subject=" .
urlencode($current_subject["id"]));
}else {
// Failure
$_SESSION["message"] = "Page creation failed.";
}
}
} else {
// This is probably a GET request
} // End: If(isset($_POST['submit']))
?>
<?php $layout_context = "admin"; ?>
<?php include("header.php"); ?>
<div id="main">
<div id="navigation">
<?php echo navigation($current_subject, $current_page); ?>
</div>
<div id="page">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Create Page</h2>
<form action="new_page.php?subject=<?php echo
urlencode($current_subject["id"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="" />
</p>
<p>Position:
<select name="position">
<?php
$page_set =
find_all_pages_for_subject($current_subject["id"], false);
$page_count = mysqli_num_rows($page_set);
for($count=1; $count <= ($page_count + 1); $count++) {
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible
<input type="radio" name="visible" value="0" /> NO
<input type="radio" name="visible" value="1" /> Yes
</p>
<p>Content:<br />
<textarea name="content" rows="20" cols="80"></textarea>
</p>
<input type="submit" name="submit" value="Create Page" />
</form>
<br />
<a href="manage_content.php?subject=<?php echo
urlencode($current_subject["id"]); ?>">Cancel</a>
</div>
</div>
<?php include("includes/footer.php"); ?>
You probably have a typo on the input HTML field. You can use:
if (isset($_POST[$field])) {
on validate_presences() function to be sure that the value exists.
When you try to do trim($_POST[$field]); you assume, the field exists in the $_POST array - for visible it does not in this case. You could move the trim to has_presence()
function has_presence($value) {
return isset($value) && trim($value) !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
Now when you will only have the trim if the variable exists.
Okay, marking the radio check button makes it work now. Thanks for all your inputs guys. It has helped me a great deal.
I keep getting a server error and I have limited it down to this code block. I must not be familiar with syntax. Can someone point out why I am getting a server error?? I posted all the code. HERE IT IS.....
<?php
// this starts the session
session_start();
$id = $_SESSION['userid'];
//this connects to the database
$con = mysql_connect("example","example","example");
mysql_select_db("example", $con);
//this is the info the user entered stored as variables
$leaguename = $_POST["leaguename"];
$members = $_POST["members"];
$leaguepassword = $_POST["leaguepassword"];
//this filters throught the variables to check against mysql injections
$leaguename = (filter_var($leaguename, FILTER_SANITIZE_STRING));
$leaguename = (filter_var($leaguename, FILTER_SANITIZE_URL));
$members = (filter_var($members, FILTER_SANITIZE_STRING));
$members = (filter_var($members, FILTER_SANITIZE_URL));
$leaguepassword = (filter_var($leaguepassword, FILTER_SANITIZE_STRING));
$leaguepassword = (filter_var($leaguepassword, FILTER_SANITIZE_URL));
//this is the variables that displays errors
$errors = "";
$result = mysql_query("SELECT * FROM League_Info WHERE League = '$leaguename'");
$result2 = mysql_fetch_array($result);
$result3 = $result2['League'];
$result4 = mysql_query("SELECT * FROM League_Info WHERE User_ID = '$id'");
$result5 = mysql_fetch_array($result4);
$result6 = $result5['User_ID'];
if ($id == "") {
$errors .= "<li>You must register or login to create a league!"; break;
} elseif ($result3 != "") {
$errors .= "<li>League Name already in use!"; break;
} elseif ($result6 != "") {
$errors .= "<li>You already have a league!"; break;
} else {
}
// no errors
if ($errors == "") {
$sql="INSERT INTO League_Info (League, User_ID, Commissioner, Year, Members, League_Password)
VALUES('$leaguename', '$id', 'y', '2012', '$members', '$leaguepassword')";
mysql_query($sql);
/* Redirect browser */
header("Location: http://www.yourfantasyfootballreality.com/invite.php");
/* Make sure that code below does not get executed when we redirect. */
exit;
} else {
}
?>
<html><head><title>Create a League</title></head>
<body>
<center><h1>Create a League</h1></center>
<center>
<div class="form" style= "width:500px; height:200px; background-color:gray; ">
<form action="createleaguevalidation.php" method="POST">
League Name: <input style="margin-left:0px;" type="text" name="leaguename" value="<?=$leaguename?>" /><br />
Number of Members: <input type="text" name="members" value="<?=$members?>"/><br>
League Password: <input type="password" name="leaguepassword" value="<?=$leaguepassword?>"><br>
<input type="submit" value="Create League" name="action">
<input type="reset" value="Reset">
</form>
<div style="background-color:#ffcccc; height:80px; width:500px;">
<?=$errors?>
</div>
</div>
<center>
</body>
</html>
If this code isn't inside a loop, then break is an error.
Your code is fine, just take out break;
To break the loop, put break; at the end of all the if statements.