PHP/MySQL won't INSERT and echo as it should? - php

What the following script does (or should do):
Connects to DB
Includes a function for creating a 5 digit code
User enters their email address
Checks if it's a valid email
Inserts the email into the 'email' column
Checks if email already exists, if so, let the user know and break script
Runs the function for creating a 5 digit code
Checks the 'unique_code' column if it already exists, if so, loop from 5 digit code creation function
If all is valid, hide the form and display the (ajax from a separate JS) thank you div
Display the unique code to the user
Everything runs, however the unique_code is not inserted into the DB and is not displayed when it does "Thank you! ".
What am I doing wrong and what needs to be modified?
Thank you!
Code
<?php
require "includes/connect.php";
function generateCode($length = 5) {
$characters = 'bcdfghjkmnpqrstvwxyz';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1)];
}
return $string;
}
$msg = '';
if($_POST['email']){
// Requested with AJAX:
$ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
try{
//validate email
if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){
throw new Exception('Invalid Email!');
}
//insert email
$mysqli->query("INSERT INTO coming_soon_emails
SET email='".$mysqli->real_escape_string($_POST['email'])."'");
//if already exists in email column
if($mysqli->affected_rows != 1){
throw new Exception('You are already on the notification list.');
}
if($ajax){
die('{"status":1}');
}
//start creating unique 5 digit code
$unique_code = "";
$inserted = false;
// Keep looping until we've inserted a record
while(!$inserted) {
// Generate a code
$unique_code = generateCode();
// Check if it exists
if ($result = $mysqli->query("SELECT unique_code FROM coming_soon_emails WHERE unique_code = '$unique_code'")) {
// Check no record exists
if ($result->num_rows == 0) {
// Create new record
$mysqli->query("INSERT INTO coming_soon_emails (email,unique_code) VALUES ('" . $mysqli->real_escape_string($_POST['email']) . "','$unique_code')");
// Set inserted to true to ext loop
$inserted = true;
// Close the result object
$result->close();
}
} else {
// Quit if we can't check the database
die('Something went wrong with select');
}
}
}
catch (Exception $e){
if($ajax){
die(json_encode(array('error'=>$e->getMessage())));
}
$msg = $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>example</title>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
<div id="container">
<form id="form" method="post" action="">
<input type="text" id="email" name="email" value="<?php echo $msg?>" />
<input type="submit" value="Submit" id="submitButton" />
</form>
<div id="thankyou">
Thank you! <?php echo $unique_code;?></p>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>

You seem to be using the private keyword outside a class definition, which isn't allowed.

Do you have a primary key on 'email' in the coming_soon_emails table? Since you've already inserted one entry for the given email address, that would keep you from inserting a second entry with the unique value.
Why not do an UPDATE instead of an INSERT once you have determined the unique key?

Related

Prevent new rows from being inserted when max records reached?

I have an SQL table where I want the max numbers of records to be 8.
I have a form to capture input via PHP and I thought I had an error handler that operates by counting the number of records in the table and, through an IF statement, punts the user back with an error if there are >= 8 records:
<?php
// Connect to database
include_once 'db_connect.php';
// Check for form action and submitted fields
if (isset($_POST["submit"])) {
$artist = $_POST["artist"];
$song = $_POST["song"];
$link = $_POST["link"];
// Link to external error handling functions
require_once 'functions.php';
// Check for empty fields
if (emptyFields($artist, $song, $link) !== false) {
header("location: index.php?error=empty");
exit();
}
// Check if record already exists
if (songExists($conn, $link, $song) !== false) {
header("location: index.php?error=duplicate");
exit();
}
// Check if link is valid
if (invalidLink($link) !== false) {
header("location: index.php?error=invalidlink");
exit();
}
// Check if table records are greater than or equal to 8
$sql = "SELECT COUNT(*) AS Num FROM songs";
$result = mysqli_query($conn, $sql);
if ($dbName['Num'] >= 8) {
header("location: index.php?error=maxreached");
exit();
}
// If no errors from above, add to table
addSong($conn, $artist, $song, $link);
}
else {
header("location: index.php?error=none");
exit();
}
<?php
include_once 'db_connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Song Submission</title>
</head>
<body>
<form action="sb_process2.php" method="POST" autocomplete="off">
<input type="text" name="artist">
<br>
<input type="text" name="song">
<br>
<input type="text" name="link">
<br>
<button type="submit" name="submit">Submit Song</button>
</form>
<?php
if (isset($_GET["error"])) {
if ($_GET["error"] == "empty") {
echo "<p>Please enter all fields.</p>";
}
else if ($_GET["error"] == "duplicate") {
echo "<p>This song has already been submitted.</p>";
}
else if ($_GET["error"] == "invalidlink") {
echo "<p>Please enter a valid URL for the Spotify link.</p>";
}
else if ($_GET["error"] == "none") {
echo "<p>Song added!</p>";
}
}
?>
I tested for my first 3 error cases and all are operating as planned (they route back with an error "code"). However, if I try to submit an entry without any errors, I just get a blank page. I ran the code through a simple PHP syntax checker and it didn't come up with any errors.

Array returns null

I'm trying at the moment to create a login with PHP and MySQL but I'm stuck. The array that's supposed to give me Data from the database only returns "Null" I used var_dumb().
This is the index.php file :
<?php
include_once './Includes/functions.php';
?>
<!DOCTYPE html
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<form method="POST">
<label>User ID :</label>
<input id="login_username" name="login_username" type="login"><br>
<label>Password :</label>
<input id="login_password" name="login_password" type="password" ><br>
<input id="login_submit" name="login_submit" type="submit">
</form>
</div>
</body>
</html>
This is the function.php file :
<?php
require_once 'dbconnect.php';
function SignIn() {
$lUser = $_POST['login_username'];
$lPassword = md5($_POST['login_password']);
$querySQL = "SELECT * FROM tblUser WHERE dtUser='$lUser' AND dtPassword='$lPassword'";
$queryResult = mysqli_query($dbc, $querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayLogin[] = $row;
}
if ($lUser == $dataArrayLogin['dtUser'] && $lPassword == $dataArrayLogin['dtPassword']) {
echo $dataArrayLogin;
$popup = "Login Succeed";
echo "<script type='text/javascript'>alert('$popup');</script>";
$_SESSION['user'] = $lUser;
header("Location: ./british.php");
} else {
echo $dataArrayLogin;
$popup = "Login Failed";
echo "<script type='text/javascript'>alert('$popup');</script>";
}
}
if (isset($_POST['login_submit'])) {
SignIn();
}
?>
Could you help me out ?
This could be, because you have no results?
Anyway, I've checked your code, and it's not good, because you are try to use this:
$dataArrayLogin['dtUser']
There is no 'dtUser' key in your $dataArrayLogin.
When you fetching the row, you are put it into a while cycle, and collect the data into an array:
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayLogin[] = $row;
}
Remove the while cycle. Simple use:
$dataArrayLogin = mysqli_fetch_assoc($queryResult);
And if you echo an array, the result will be Array. Use var_dump instead.
in your html form, you don't have <form method="POST" action="SignIn">. so when you submit the form, its not going somewhere.
You need to start debugging your script. Below are the steps I would take:
Do a var_dump() on the $_POST to see if it contains all values you want
echo the $querySQL to see if all values are put in correctly
Check your database if it actually contains the record with which you are trying to login
Fetch mysql errors using mysqli_error();
That should bring your error to light.
Edit:
I often find it usefull to place some echos throughout my script to find out what parts of the code are being accessed and what parts are being skipped.
I would add a LIMIT 1 to your query as there should only be one user with the entered credentials. This way you'll also be able to skip the while loop.
Change query like this
$querySQL = "SELECT * FROM tblUser WHERE dtUser=' ".$lUser." ' AND dtPassword=' ".$lPassword." ' ";

PHP update not working

I'm building a custom CMS and I've written a script that is supposed to edit already existing information in my database.
I've used the code for a different database before and it has worked without any troubles, but I've changed the index names to reference a new database and now it won't work.
The information is displayed on a page with an 'edit' button the links the user to a html form which displays the selected piece of info in a text box.
There's no problem displaying the info in the form, but once the submit button is pressed the code does not execute it, and the info is not updated and no error message is displayed..
so I'm fairly sure there's a problem somewhere in this... (Ignore the comments)
if (isset($_GET['edittimeslot']))
{
$timeslotid = $_GET['timeslotid'];
try
{
$sql = "SELECT timeslotid, Time FROM timeslots WHERE timeslotid = timeslotid" ;
//echo $sql;
$data = $pdo->query($sql);
$timeslots = $data->fetch();
//print_r($acts);
}
catch(PDOException $e)
{
echo "this didnt work" .$e->getMessage() ;
}
$pagetitle = 'Edit your date here';
$timeslotid = $timeslots['timeslotid'];
$time = $timeslots['Time'];
$button = 'Edit timeslot';
include 'timeslot.form.php';
exit();
}
// is all of the requested feilds appropiate
if (isset($_POST['submit']) && $_POST['submit'] == 'Edit timeslot')
{
// get the form data that was posted ready to insert into the stage database
$timeslotid = $_POST['timeslotid'];
$time= htmlspecialchars($_POST['time']);
try
{
// prepare the query to insert data into stages table
$sql = "UPDATE timeslots
SET Time = :Time,
WHERE timeslotid = :timeslotid";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Time', $time);
$stmt->bindParam(':timeslotid', $timeslotid);
$stmt->execute();
}
catch(PDOException $e)
{
//error message goes here if the insert fails
}
}
HTML:
<!doctype html>
<head>
<style type="text/css">
.container {
width: 800px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<h1><?php echo $pagetitle;?></h1>
<form action='.' method='post'>
<!-- stage name -->
<p><label for='time'> What is the timeslots you would like to add? 00:00-00:00 </label></p>
<p><input type='text' name='time' id='time' value='<?php echo $time;?>'> </p>
<p><input type='submit' name='submit' value='<?php echo $button;?>'></p>
</form>
</div>
</body>
Shouldn't WHERE timeslotid = timeslotid be WHERE timeslotid = $timeslotid ?
Also, using a form value directly is a bad idea. Use it at least like $timeslotid = (int)$_GET['timeslotid'];.
Okay one thing that I see right away is this line:
$timeslotid = $_POST['timeslotid'];
Where is that form field in your form? I don't see it anywhere. Also try to assign the execution to a variable and var_dump it so you can see if it returns TRUE or FALSE:
$success = $stmt->execute();
var_dump($success);
Furthermore make sure that you DB column is named Time and not time with all lowercase.

Undefined variable session in a login system

Hi I am trying to develop a login sistem but I seem to be getting an error on a condition.This is my code:
//header.php
if($_SESSION['signed_in']){
echo 'Hello' . $_SESSION['user_name'] . '. Not you? Sign out';
}
else{
echo 'Sign in or create an account.';
}
//Signin.php
if(mysql_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysql_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_name'] . '. Proceed to the forum overview.';
}
The error is pointed on the first condition : if($_SESSION['signed_in']) and it says that:
Notice: Undefined variable: _SESSION in C:\xampp\htdocs\Tutorials\Forum\header.php on line 21
How can I corect this?
EDIT:session_start() is included at the top of the header.php file in the doctype and header.php is included in Signin.php
Full Code:
header.php
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="nl" lang="nl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="A short description." />
<meta name="keywords" content="put, keywords, here" />
<title>PHP-MySQL forum</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<h1>My forum</h1>
<div id="wrapper">
<div id="menu">
<a class="item" href="/forum/index.php">Home</a> -
<a class="item" href="/forum/create_topic.php">Create a topic</a> -
<a class="item" href="/forum/create_cat.php">Create a category</a>
<div id="userbar">
<div id="userbar">
<?php
if($_SESSION['signed_in']){
echo 'Hello' . $_SESSION['user_name'] . '. Not you? Sign out';
}
else{
echo 'Sign in or create an account.';
}
?>
</div>
</div>
<div id="content">
Signin.php
<?php
//signin.php
include 'conn.php';
include 'header.php';
echo '<h3>Sign in</h3>';
//first, check if the user is already signed in. If that is the case, there is no need to display this page
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can sign out if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form method="post" action="">
Username: <input type="text" name="user_name" />
Password: <input type="password" name="user_pass">
<input type="submit" value="Sign in" />
</form>';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Varify if the data is correct and return the correct response
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['user_name']))
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'The password field must not be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo 'Uh-oh.. a couple of fields are not filled in correctly..';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
else
{
//the form has been posted without errors, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "SELECT
user_id,
user_name,
user_level
FROM
users
WHERE
user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
AND
user_pass = '" . sha1($_POST['user_pass']) . "'";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysql_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysql_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_name'] . '. Proceed to the forum overview.';
}
}
}
}
}
include 'footer.php';
?>
Before you store something into the session, the variable $_SESSION['signed_in'] will be empty. The warning occurs because you ask for this value, but nothing is inside.
if (isset($_SESSION['signed_in']) && $_SESSION['signed_in'])
{
}
To avoid the warning, you should first check if the variable exists, then you can read from it. Of course this is a bit cumbersome, so most developers create a function just for reading safely from an array.
Edit:
Actually the problem above would lead to another message...
Notice: Undefined index: ...
...so it is as Mob said, the variable $_SESSION doesn't exist at all, because no session was started. I will let this answer stay, because this will be the next pitfall.
There's no session_start(); That's the reason, you have to always declare that befoe using sessions in PHP.

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?

Categories