I have a php posting script and I need it to grab the data from the database. Here's the script:
<?php
error_reporting(E_ALL);
session_start();
// If the session vars aren't set, try to set them with a cookie
if (!isset($_SESSION['user_id'])) {
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cheesecake Productions - Post Topic</title>
<link rel="stylesheet" type="text/css" href="include/style/content.css" />
</head>
<body>
<?php
include ("include/header.html");
include ("include/sidebar.html");
?>
<div class="container">
<?php
require_once('appvars.php');
require_once('connectvars.php');
// Make sure the user is logged in before going any further.
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('could not connect to mysql '.mysqli_connect_error());
// Grab the profile data from the database
$query = "SELECT first_name FROM ccp2_user WHERE first_name = '" . $_SESSION['user_id'] . "'";
$data = mysqli_query($dbc, $query);
///////////////////////////
///What must I do after////
//getting the data from////
//database. I am new to////
//PHP//////////////////////
//////////////////////////
$row = mysqli_fetch_array($data);
$first_name = mysqli_real_escape_string($dbc, trim($_POST['first_name']));
if (isset($_POST['submit'])) {
// Grab the profile data from the POST
$post1 = mysqli_real_escape_string($dbc, trim($_POST['post1']));
// Update the profile data in the database
if (!$error) {
if (!empty($post1)) {
// Only set the picture column if there is a new picture
$query = "INSERT INTO `ccp2_posts` (`first_name`, `post_date`, `post`) VALUES ('$first_name', NOW(), '$post1')";
mysqli_query($dbc, $query);
// Confirm success with the user
echo '<p>Your post has been successfully added. Would you like to view all of the posts?</p>';
mysqli_close($dbc);
exit();
}
else {
echo '<p class="error">You must enter information into all of the fields.</p>';
}
}
} // End of check for form submission
else {
echo '<p>Grr</p>';
}
mysqli_close($dbc);
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MM_MAXFILESIZE; ?>" />
<fieldset>
<legend>Post Here:</legend>
<label type="hidden" for="post1">Post Content:</label><br />
<textarea rows="4" name="post1" id="post1" cols="50">Post Here...</textarea><br />
</fieldset>
<input type="submit" value="Save Post" name="submit" />
</form>
</div>
<?php
include ("include/footer.html");
?>
</body>
</html>
This script is supposed to grab first_name from the database and it is not. Help?
Edit: There's the whole code.
Many things are strange with your code
I believe it's blank because one of the if/else is messed up:
if (isset($_POST['submit'])) {
....
}
else {//here
else {
echo '<p class="error">There was a problem accessing your profile.</p>';
}
}
then you have $error variable that have no meaning
$error = false;
Then you have in your form :
<input type="text" id="first_name" name="first_name" value="" /><br />
but you dont want to grab it from there, but the database:
$query = "SELECT first_name FROM ccp2_user
WHERE user_id = '" . $_SESSION['user_id'] . "'";
Then your wanna grab $last_name From the post
$last_name = mysqli_real_escape_string($dbc, trim($_POST['last_name']));
but you don't have it in your form
Also this part:
if (!empty($first_name) && !empty($post1)) {
// Only set the picture column if there is a new picture
if (!empty($new_picture)) {
$query = "INSERT INTO `ccp2_posts` (`first_name`, `post_date`, `post`)
VALUES ('$first_name', NOW(), '$post1')";
}
else {
$query = "INSERT INTO `ccp2_posts` (`first_name`, `post_date`, `post`)
VALUES ('$first_name', NOW(), '$post1')";
}
}
You you have a condition on new_picture Where did you initialize that. Why is it the same insert query again?
Don't you need quote around that?
you have so many issues here, I advice you to trouble shoot step by step. and redesign tis whole thing.
I put something real quick together that works on my system.
This is a basic method and I mean basic, so you'll need to do the rest.
Just change the DB credentials to your own, and the the_user_id assigned to $_SESSION['user_id']
It's the best I can do to help.
<?php
$DB_HOST = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";
$dbc = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($dbc->connect_errno > 0) {
die('Connection failed [' . $dbc->connect_error . ']');
}
session_start();
$_SESSION['user_id'] = "the_user_id"; // change this to the user's id
// You can use * also as the line from below
// $sql = $dbc->query("SELECT * FROM `ccp2_user` WHERE `user_id` = '" . $_SESSION['user_id'] . "'");
$sql = $dbc->query("SELECT `first_name` FROM `ccp2_user` WHERE `user_id` = '" . $_SESSION['user_id'] . "'");
while($row= mysqli_fetch_array($sql))
{
echo $row['user_id'];
}
// for testing purposes
// var_dump($_SESSION['user_id']);
// var_dump($_SESSION);
mysqli_close($dbc);
Its here,
require_once('appvars.php');
require_once('connectvars.php');
One of these file must not be set or php cant find these file. So as it says 'require' which means till we dont get this file it will not proceed. so it halt the execution there itself.
try it with :
include('appvars.php');
include('connectvars.php');
It you see the page then problem is here itself.
Related
i already made a sign up form and everything goes well.
Now i'm trying to do login and i don't succeed.
log1.html
<!DOCTYPE html>
<html>
<head>
<title>RegPage</title>
</head>
<body>
<form action ="log2.php" method="post">
email: <input type="text" name ="email">
<br/>
password: <input type="password" name="password">
<input type = "submit" value = "insert">
</form>
</body>
</html>
log2.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "pilot";
$conn = new mysqli($servername, $username, $password,$databasename);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$email=$_POST['email'];
$password=$_POST['password'];
$comparepass="SELECT password FROM dbinvestor where email=#email";
if ($comparepass==$password)
{
echo 'logged in !';
}
else
{
echo ' oops';
}
header ("refresh:10;url=log1.html");
?>
DB:
DB image
no matter what i instert in textbox the output is alway :
connect successfully oops
Why it always "go" to the else also if the password and email are correct ?
You are defining a SQL query but you don’t actually run it against your database...
$comparepass="SELECT password FROM dbinvestor where email=#email";
if ($comparepass==$password)
{
echo 'logged in !';
}
You need to execute the query and fetch the result to compare it with the posted value. Here is bit of code that demonstrates how to proceed, using bind parameters (disclaimer : you seem to be storing clear password in database... just don’t).
$sql="SELECT 1 FROM dbinvestor where email=? and password=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
$result = $stmt->get_result();
if (!$result) {
echo 'error: ' . $conn->errno . ' - ' . $conn->error)
} else {
if ($result->num_rows == 1) {
echo 'logged in !';
} else {
echo ' oops';
}
}
You can try this :
$comparepass="SELECT * FROM dbinvestor where email='$email' and password='$password'";
$compare_exe=$this->conn()->query($comparepass); //use your db link
$num_rows=$compare_exe->num_rows; //get row counter, if exist will return 1 else 0
if($num_rows>0){
echo 'logged in !';
}else{
echo 'opps';
}
When I'm trying to connect to a database in order to search for a username and password, it seems that running 'echo' command for any option kills the entire page and doesn't execute the rest of the code.
Here is my PHP file:
<html>
<body>
<?php
//setting variables for connecting to database
error_reporting(0);
$host = 'localhost';
$username = 'root';
$password = '';
$db = 'aquamandb';
date_default_timezone_set('America/Chicago');
//connecting to the database
$connect = new mysqli($host,$username, $password, $db) or die("Unable to connect");
//getting the username, user type, and password for sanitizing
$_US_username = $_GET['username'];
$_US_password = $_GET['password'];
//sanitize the variable to remove SQL statements that could drop the database potentially.
$username = mysql_real_escape_string($_US_username);
$password = mysql_real_escape_string($_US_password);
$sql = "SELECT * FROM user WHERE username = '$username' AND password = '$password'";
$result = mysql_query($sql);
//Send alert to page if there is not a match found between username password and user type
if(!$result)
{
die('Could not get data: ' . mysql_error());
}
else
{
$row = mysql_fetch_array($result);
if($row['type'] == 1)
{
echo '<form name = "auto" action = "../admin-dash.html" method = "POST">';
}
else if($row['type'] == 2)
{
echo '<form name = "auto" action = "../sigadmin-dash.html" method = "POST">';
} else
{
echo '<form name = "auto" action = "../sigusr-dash.html" method = "POST">';
}
}
?>
Note: I'm only posting a link to the PHP code because the file would never format correctly and would actually cause the same issue when I tried to use it on my website.
The issue is at Line 37. The echo statement stops, it doesn't create the form, and it just prints the rest of the elseif statements in regular text on the live web page.
If there are any clues as to what I am doing wrong (if I'm formatting something wrong) would be fantastic.
Not sure why you don't just put the form inside the html and call $_POST or $GET Inside php it would be way more simple that way. The error I see is right before line 37 where you forgot your(";") but even fixed it doesn't print the form i dont even think its processing your if but not sure. Also you should use prepared statements instead of mysql_real_escape_string , also your using mysqli to initially connect then you use mysql while escaping. .Try something like this:::::
<!doctype html>
<html>
<body>
<form action = "whatever.php method = "post">
<input type = "email" name = "email" />
<input type = "password" name = "password" />
<input type = "submit" name = "submit" value = "insert" />
</form>
<?php
// connect to the server
$conn = new mysqli('localhost', 'usename', 'password', 'database');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
} else {
echo "your connection was successful";
}
if($_POST && isset($_POST['submit'], $_POST['name'] )) {
$email = ( $_POST["email"]);
$pass = ($_POST["password"]);
$query = mysqli_prepare($conn, "SELECT pass FROM database
WHERE email = ? ");
mysqli_stmt_bind_param($query,'s', $email );
mysqli_stmt_execute($query);
mysqli_stmt_bind_result($query, $email);
if(mysqli_stmt_fetch($query)) {
echo "<br />";
echo "SUCCESS at query";
if (password_verify($input, $id)) {
echo "matching pass" . header("Location: inserh.php");
} else{
echo "not a match";
}
}
mysqli_stmt_close($query);
}
mysqli_close($conn);
Hope this helps Also this script verifies the hashed password using bcrypt!
There is a missing semi colon # the end of line 34:
$row = mysql_fetch_array($result);
$row = mysql_fetch_array($result) is missing a ; and is crashing your script
I am in the process of making a login screen so once the session has been set a person can access various pages on my site.
It seems, however, that when I send the username and password to be compared with what I have in the MySQL database the results come back empty.
MySQL table:
Id, Username, Password, Email, group
1, bunbun, hashedpassword, example#email.com, admin
PHP code:
<?php
include_once("functions/con-open.php");
if (isset($_POST['username']))
{
$name = $_POST['username'];
//$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$password = $_POST['password'];
$name = mysql_real_escape_string($name);
$password = mysql_real_escape_string($password);
}
function LOGIN($Name, $Password)
{
$conn = new mysqli(HOST,USER,PASSWORD,DATABASE);
if ($conn->connect_errno)
{
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
if ($result = $conn->query("SELECT * FROM persons WHERE Username='$Name'", MYSQLI_USE_RESULT))
{
printf("Select returned %d rows.\n", $result->num_rows);
echo "<br>Name Dump<br>";
var_dump($Name);
echo "<br>Password Dump <br>";
var_dump($Password);
echo "<br>";
echo "<br>";
var_dump( $result);
$result->close();
}
else
{
echo"no details returned <br>";
var_dump( $result);
$result->close();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login</title>
<link type="text/css" href="css.css" rel="stylesheet" />
</head>
<body>
<form action="login.php" method="post" name="login-form">
Email: <input type="text" name="username" /><br>
Password: <input type="password" name="password"/>
<input type="submit" value="Login"/>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
LOGIN($NAME, $PASSWORD);
}
?>
</body>
</html>
The result is
Select returned 0 rows.
This is what I have typed in username field:
This is what I have typed in password field:
Name from DB:
Password from DB:
object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(5) ["lengths"]=> NULL ["num_rows"]=> int(0) ["type"]=> int(0) }
Any ideas where I am going wrong?
The column for my hash is Vchar(255) I gave it enough room from the beginning.
Update! This maybe more serious, I have changed the code above to reflect the excellent answer from maytham. however it is still returning 0 results
I took the liberty of adding within the loop, if (isset($_POST['username']))
echo "This is what the value name is: ".$name."<br>";
and the same just before i call LOGIN($name, password); to see if $name is set, it is.
however between the function being called and $Name being used in the sql query the value is empty. Not sure why that would be I'll have to debug my php installation to see if there is any bugs.
Here is what I have observed and fix it for you.
Follow the steps and it should works:
Step A
if ($result = $conn->query("SELECT * FROM persons WHERE Username='$Name'", MYSQLI_USE_RESULT))
To
if ($result = $conn->query("SELECT * FROM persons WHERE Username = '$Name'"))
Step B
The code presented in the question, the function LOGIN need to end with }
function LOGIN($Name, $Password)
Step C (Optional)
When I test I have changed password to plain text to be sure every thing is working, but it is up to you.
$password = $_POST['password'];
Step D
At the beginning of the code I will put if statement
if (isset($_POST['username']))
{
$name = $_POST['username'];
// disable for testing
//$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$password = $_POST['password'];
}
Step E (Optional)
I suggest you change all variables like $USERNAME to $username
Step F
Try to protect your inputs from SQL injection by adding mysql_real_escape_string:
$name = mysql_real_escape_string($name);
$password = mysql_real_escape_string($password);
thank to user #ibu for noticing that
Finally
Here is the full workable code with my modification:
<?php
if (isset($_POST['username']))
{
$name = $_POST['username'];
//$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$password = $_POST['password'];
$name = mysql_real_escape_string($name);
$password = mysql_real_escape_string($password);
}
function LOGIN($Name, $Password)
{
$conn = new mysqli("localhost", "root", "", "test");
if ($conn->connect_errno)
{
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
if ($result = $conn->query("SELECT * FROM persons WHERE Username = '$Name'"))
{
$row = $result->fetch_assoc();
printf("Select returned %d rows.\n", $result->num_rows);
echo "<br />";
echo "This is what I have typed in username field: " . $Name;
echo "<br />";
echo "<b>Name from DB: </b>" . $row['Username'] . "<br />";
echo "<b>Password from DB: </b>" . $row['Password'] . "<br />";
echo "<br />";
var_dump($result);
$result->close();
} else
{
echo "no details returned <br>";
var_dump($result);
$result->close();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Login</title>
<link type="text/css" href="css.css" rel="stylesheet"/>
</head>
<body>
<form action="login.php" method="post" name="login-form">
Email: <input type="text" name="username"/><br>
Password: <input type="password" name="password"/>
<input type="submit" value="Login"/>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
LOGIN($name, $password);
}
?>
</body>
</html>
Here is a test shot from my screen:
Note: When all this mentioned, this does not mean the code or what is presented is a good or perfect solution. There is a lot you have to think about when building a login mechanism. The code is also vulnerable for SQL injection you need and have to do a lot work. I encourage you to look at:
Link1: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Link2: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
Link3: http://php.net/manual/en/mysqli.quickstart.statements.php
You have either edited data or need a trim () for invisible chars.
string(13) "bunbun"
That's not 13 chars in length
There's no reason as it currently stands that the query should dump like it is.
As others have noted. Be aware if SQL injection too
im currently struggling to get my PHP log in to work. Iv used a separations of concerns to structure my php.
Iv already set up in my database a Users table with id, username and password values.
I dont think that there is a problem connecting to my database as i've used the same code in other projects and it works there.
This is my user_repository.php:
<?php
require_once "database.php";
function authenticate_user($username, $password, &$error) {
$sql = "select * from Users where username= '${username}'";
$sql .=" and password='{password}'";
$result = query($sql);
if ($result->num_rows!=1) {
$error = "Username or password was incroeect.";
return null;
}
return $result-> fetch_assoc();
}
function get_user_by_id($id, &$error) {
$sql = "select * from Users where id={$id} limit 1;";
$result = query($sql);
return $result->fetch_assoc();
}
?>
This is my database.php:
<?php
define("SQLHOST", "localhost");
define("SQLUSER", "b3006796");
define("SQLDB", "b3006796_db3");
define("SQLPASSWORD", "*******");
function connect_to_database () {
$mysqli = new mysqli(SQLHOST, SQLUSER, SQLPASSWORD, SQLDB);
if($mysqli->connect_errno) {
echo "failed to connect to mysql: ".$mysqli->connect_errno;
exit();
}
return $mysqli;
}
function query ($sql) {
$mysqli = connect_to_database();
$result = $mysqli->query($sql);
if (!$result) {
echo "failed to run query: ".$mysqli->error;
exit();
}
return $result;
}
?>
This is my index.php:
<?php
session_start();
require_once "user_repository.php";
$error = null;
if (isset ($_POST["username"]) && isset($_POST["password"])) {
$username = $_POST ["username"];
$password = $_POST ["password"];
// Get the assoc array for the user.
$user = authenticate_user($username, $password, $error);
//No error means valid password here.
if (!$error) {
$_SESSION['currentUser'] = $user['id'];
header("location:account.php");
exit();
}
}
?>
<html>
<head>
<title> DIWA Login </title>
</head>
<body>
<h1>login</h1>
<form method="post">
Username:<input name="username"/>
Password:<input name="password" type="password"/>
<input type="submit"/>
<?php if ($error);?>
<p><?php echo $error; ?></p>
</form?
</body>
</html>
And this is my Account.php:
<?php
session_start();
require_once "user_repository.php";
$error = null;
if (!isset($_SESSION["currentUser"])) {
header ("Location: login.php");
exit();
}
$user = get_user_by_id($_SESSION["currentUser"], $error);
?>
<html>
<head>
<title> DIWA Account </title>
</head>
<body>
<h1> Account </h1>
<p> User ID: <?php echo $user["id"]; ?></p>
</body>
</html>
Thanks
If your problem is that you cannot log in, then there is at least one bug:
`$sql .=" and password='{password}'";`
you omitted "$" at 'password', it should be
$sql .=" and password='{$password}'";
Also:
$sql = "select * from Users where username= '${username}'";
should be:
$sql = "select * from Users where username= '{$username}'";
EDIT: I think I figured out what is happening! The Variable $string is set to be a post value, so when I run the comment code it is overriding the Post value with its own and setting $string to be nothing, breaking the page. Any ideas how to fix?
I'm running a piece of code for a simple website that should submit a comment entered into a form into the database, but when I click the submit button for the comment it just gives me this error message:
Database access failed1: 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
The code for the page in question is:
<?php
require_once('checklog.php');
require_once("functions.php");
require_once('../Website/recaptcha/recaptchalib.php');
//Include external php files. Functions contains functions, Checklog redirects the user to the login page if they are not logged in. Checklog also contains session_start(). If you remove it make sure to add session_start() to this page.
$db_hostname = 'localhost';
$db_database = 'removed';
$db_username = 'removed';
$db_password = 'removed';
$db_status = 'not initialised';
$str_result = '';
$str_options = '';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
$string = $_POST ['filmID'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT FilmName, GenreName, DirName, Synopsis FROM Films JOIN Genres JOIN Directors WHERE Directors.DirID = Films.DirID AND Films.GenreID = Genres.GenreID AND Films.FilmID = $string";
$resultcount = 1;
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed1: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$FilmName = $row['FilmName'];
$GenreName = $row['GenreName'];
$DirName = $row['DirName'];
$Synopsis = $row['Synopsis'];
}
mysqli_free_result($result);
$query = "SELECT username, Rating, Comment FROM Comments JOIN Users WHERE Comments.UserID = Users.UserID AND Comments.FilmID = $string";
$commentnum = 1;
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed2: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_comments .= "<p>" . $commentnum . " - Review by " . $row['username'] . ": " . $row['Comment'] . " [" . $row['Rating'] . "/5]</p>";
$commentnum = $commentnum + 1;
}
mysqli_free_result($result);
if(trim($_POST['submit']) == "Submit"){
$privatekey= "6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
$message = " ";
if (!$resp->is_valid) {
//incorrect entry
$message = "The reCAPTCHA wasn't entered correctly. Go back and try again.
(reCAPTCHA said: " . $resp->error . ")";
//recaptcha validation
} else {
//Submit the reviews
$comment = clean_string($db_server, $_POST['comment']);
$rating = clean_string($db_server, $_POST['rating']);
$user = $SESSION['UserID'];
if ($comment != '') {
$queryreview = "INSERT INTO Comments (Comment, Rating, UserID, FilmID) VALUES ('$comment', '$rating', '$user', '$string')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $queryreview) or
die("Insert failed: " . mysqli_error($db_server));
}
}
}
?>
<html>
<head>
<title>View individual film details.</title>
</head>
<body>
<h1>Welcome to the site, <?php echo $_SESSION['username']; ?> ! You are user ID <?php echo $_SESSION['userid'] ?>.</h1>
<p>This film is called <?php echo $FilmName ?> and is a <?php echo $GenreName; ?> film directed by <?php echo $DirName; ?></p>
<p>Synopsis: <?php echo $Synopsis; ?> </p></body>
<p>Reviews:
<?php echo $str_comments ?></p>
<form id="frmComments" action="viewfilm.php" method="post">
<p>Have you seen this movie? Leave a review and tell other users what you thought.</p>
review: <textarea rows="2" cols="30" name="comment"></textarea> </p>
<p>Rating: <select name="rating">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<?php
$publickey = "6Lem4-gSAAAAAMHLAVbieIknMtUZo71ZKzzCkoFN";
echo recaptcha_get_html($publickey);
?>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
The piece of code that should be running the comment insertion is
if(trim($_POST['submit']) == "Submit"){
$privatekey= "6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
$message = " ";
if (!$resp->is_valid) {
//incorrect entry
$message = "The reCAPTCHA wasn't entered correctly. Go back and try again.
(reCAPTCHA said: " . $resp->error . ")";
//recaptcha validation
} else {
//Submit the reviews
$comment = clean_string($db_server, $_POST['comment']);
$rating = clean_string($db_server, $_POST['rating']);
$user = $SESSION['UserID'];
if ($comment != '') {
$queryreview = "INSERT INTO Comments (Comment, Rating, UserID, FilmID) VALUES ('$comment', '$rating', '$user', '$string')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $queryreview) or
die("Insert failed: " . mysqli_error($db_server));
}
}
}
But as you can see by the "1" included in the error message, the error is pointing to the earlier query that is used to generate the page content. Thing is this query does work, it is only after clicking submit on a comment that I get this error.
Yes, the probem is indeed the $string variabe that is being sent empty.
There are different ways to solve this issue here are some ideas:
Use a hidden field in the form where the value of the posted filmID is stored and sent again after submitting.
Store the filmID value in the Session global.
Hope this helps
if you need to give string in your values then set variable inside quotation like this:
Change
$queryreview = "INSERT INTO Comments (Comment, Rating, UserID, FilmID) VALUES ('$comment, $rating, $user, $string')"
to
$queryreview = "INSERT INTO Comments (Comment, Rating, UserID, FilmID) VALUES ('$comment', '$rating', '$user', '$string')"