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')"
Related
EDIT: problem has now been solved, ive provided my original and my fixed versions of the PHP code below. honestly not sure what the difference is, i've never used PHP before but hopefully this helps someone!
looking for some help.
i'm doing university coursework at the moment and need help with one element.
when i am trying to pass data which is taken in from a web form, the page gives an error if i use the following statement:
echo $db_connection->error;
the error that it gives is:
Parse error: syntax error, unexpected '$useremail' (T_VARIABLE) in (directory goes here, i've removed it)
i cant figure out how to fix this error. if i echo the SQL insert query and copy+paste it into the database it works perfectly.
any help would be much appreciated.
edit:
the fixed full PHP code is as follows:
<?php
require_once "db.php";
// below code checks whether the form is submitted
// using the POST method or not
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// the form is submitted using the POST method
// now proceed to process the form's data
//$errPass = $errEmail = $errName = $errCVtype = $errCompanyname = "";
//$pass = $email = $name = $usercomment = $cvtype = $companyname = "";
//$pass = mysqli_real_escape_string($db_connection,
$_POST["password"]);
// $salt = "TheQuickBrownFoxJumpedOverTheMoonTwice";
// $data = $pass . $salt;
//$password = crypt($data);
//these commented lines are redundant (left in by lecturer)
$useremail = mysqli_real_escape_string($db_connection, $_POST["email"]);
$fname = mysqli_real_escape_string($db_connection, $_POST["fname"]);
$sname = mysqli_real_escape_string($db_connection, $_POST["sname"]);
$cname = mysqli_real_escape_string($db_connection, $_POST["cname"]);
$usercomment = mysqli_real_escape_string($db_connection, $_POST["comment"]);
$cvtype = mysqli_real_escape_string($db_connection, $_POST["cvchoice"]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP and MySQLi Thank you message.</title>
<link rel="stylesheet" href="../CSS/process_cv.css">
</head>
<body>
<div id="container">
<div id="text-field">
<section>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST" )
{
$qry = "insert into cv_test(email, fname, sname, cname, usercomment, cvrequested)
values('$useremail', '$fname', '$sname', '$cname', '$usercomment', '$cvtype');";
$res = $db_connection->query($qry);
if($res)
{
echo "<p id='Title'>Thank you for requesting to see my CV.</p>";
echo "<p id='Name'>Your Name: <strong>".$fname."</strong></p>";
echo "<p id='Email'>Your Email: <strong>".$useremail."</strong></p>";
echo "<p id='Company'>Your Company Name: <strong>".$cname."</strong></p>";
echo "<p id='Comment'>Your Comment: ".$usercomment."</p>";
echo "<p id='CV'><a href='REMOVED PRIVATE URL";
if ($cvtype === 'short')
echo "Short_CV";
else
echo "Long_CV";
echo ".pdf' target='_blank'>View my ".$cvtype." CV</a></p>";
//echo "<p id='image_map'><a href='../image_map.html'>Return To Image_Map</a></p>";
exit();
}
else
{
echo "<p>Error occurred, kindly try again later.</p>";
//echo "<p><a href='../image_map.html'>Return To Image_Map</a></p>";
exit();
}
}
$db_connection->close();
?>
</section>
</div>
</div>
</body>
</html>
the original code was:
<?php
require_once "db.php";
// below code checks whether the form is submitted
// using the POST method or not
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// the form is submitted using the POST method
// now proceed to process the form's data
//$errPass = $erruseremail = $errfname = $errsname = $errcname = $errusercomment = $errcvtype = "";
//$pass = $useremail = $fname = $sname = $cname = $usercomment = $cvtype = "";
//$pass = mysqli_real_escape_string($db_connection, $_POST["password"]);
//$salt = "TheQuickBrownFoxJumpedOverTheMoonTwice";
//$data = $pass . $salt;
//$password = crypt($data);
$useremail = mysqli_real_escape_string($db_connection, $_POST["email"]);
$fname = mysqli_real_escape_string($db_connection, $_POST["fname"]);
$sname = mysqli_real_escape_string($db_connection, $_POST["sname"]);
$cname = mysqli_real_escape_string($db_connection, $_POST["cname"]);
$usercomment = mysqli_real_escape_string($db_connection, $_POST["comment"]);
$cvtype = mysqli_real_escape_string($db_connection, $_POST["cvchoice"]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP and MySQLi Thank you message.</title>
</head>
<body>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$qry = "insert into cv_test(email, fname, sname, cname, usercomment, cvrequested)<br>
values('$useremail', '$fname', '$sname', '$cname', '$usercomment', '$cvtype');";
echo $qry . "<br>";
$res = $db_connection->query($qry);
if($res)
{
echo "<p>Thank you for requesting to see my CV.</p>";
echo "<p> Your name: <strong>".$fname." ".$sname."</strong></p>";
echo "<p>Your Company Name: <strong>".$cname."</strong></p>";
echo "<p>Your email: ".$useremail."</p>";
echo "<p>Your Comment: ".$usercomment."</p>";
echo "<p><a href='REMOVED PRIVATE URL";
if ($cvtype === 'short')
echo "Short_CV";
else
echo "Long_CV";
echo ".pdf' target='_blank'>View my ".$cvtype." CV</a></p>";
exit();
}
else
{
echo "<p>Error occurred, kindly try again later.</p>";
exit();
}
}
$db_connection->close();
?>
</body>
</html>
The issue was in your sql text, there's a 'br' tag.
"insert into cv_test(email, fname, sname, cname, usercomment, cvrequested)<br>
values('$useremail', '$fname', '$sname', '$cname', '$usercomment', '$cvtype');"
That was causing the error.
In your new sql test, you have removed the 'br' tag.
"insert into cv_test(email, fname, sname, cname, usercomment, cvrequested)
values('$useremail', '$fname', '$sname', '$cname', '$usercomment', '$cvtype');"
'br' is not part of sql syntax
i need to set a session called BusinessID in php but its not working on my live server , i cannot figure out what is wrong with it
what happens is that it executes the first query but does not set session and redirect to dashboard.php
heres the code
<?php
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
if(isset($_POST["register"]))
{
$company = $_POST["company"];
$address = $_POST["address"];
$contact = $_POST["contact"];
$city = $_POST["city"];
$tags = $_POST["tags"];
$email = $_POST["email"];
$password = $_POST["password"];
$sql="INSERT INTO business(`companyname`, `email`, `password`, `address`, `tel`, `city`, `tag`,`status`, `created_at`,`type`)
VALUES('$company','$email','$password','$address','$contact','$city','$tags','unblocked',CURRENT_TIMESTAMP,'Null')";
if (mysqli_query($link, $sql)) {
$query = "select id from business where email='$email' and password='$password'";
$result = mysqli_query($link,$query);
if (mysqli_fetch_assoc($result))
{
$_SESSION["businessID"] = $result[0]["id"];
header("Location: dashboard.php");
}
else
{
header("Location: login.php?Invalid= Please Enter Correct User Name and Password ");
}
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// Close connection
mysqli_close($link);
?>
You have missed
session_start();
after php tag
You can set the Session first in the code.
<?php
// Start the session
session_start();
?>
Check this one. https://www.w3schools.com/php/php_sessions.asp
I've been reluctant to come back to Stackoverflow to ask this question. It's definitely been asked many times over, but every answer hasn't been able to fix the problem. I've attempted the Header() fix: https://stackoverflow.com/a/18820079/3831297 to no avail and now I have been trying to instead just validate and submit from the same page.
When I was using the Header redirect nothing would happen, no redirect to the next page while also not giving any errors for a reason. Which leaves me with the method below.. A mess of code that I've spent 60+ hours on trying to get to work from answers found on here as well as other websites.
What I've been trying to do with this version is validate with:
if(empty()) {
display error
}else{
variable = true
if(variable = true){
post to database
}
I apologize for the repeated question as well as for my complete lack of knowledge. I am learning as I go with these hands-on projects.
<?php
if (mysqli_connect_errno()) {
echo "Connection to the database failed! Submitting a story will not work! Try again in a few minutes!" . mysqli_connect_error();
}else{
echo "<br>";
echo "<h4>" . "Database connected successfully... It is safe to submit a story!" . "</h4>";
}
$TitleErr = $StoryErr = $AuthorErr = $DateErr = "";
$Title = $Story = $Author = $Date = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Title"])) {
$TitleErr = "Title is required!";
}else{
$valid1 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Story"])) {
$StoryErr = "Story is required!";
}else{
$valid2 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Author"])) {
$AuthorErr = "Author is required!";
}else{
$valid3 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["Date"])) {
$DateErr = "Date is required!";
}else{
$valid4 == true;
}
}
if ($valid1 = $valid2 = $valid3 = $valid4 = true) {
$Title = mysqli_real_escape_string($con, $_POST['Title']);
$Date = mysqli_real_escape_string($con, $_POST['Date']);
$Author = mysqli_real_escape_string($con, $_POST['Author']);
$Story = mysqli_real_escape_string($con, $_POST['Story']);
$sql="INSERT INTO Moderate (Title, Story, Author, Date)
VALUES ('$Title', '$Story', '$Author', '$Date')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}else{
echo "<br>";
echo "Story submitted for moderation!";
}
}
mysqli_close($con);
//Insert into database
//$sql="INSERT INTO Moderate (Title, Story, Author, Date)
//VALUES ('$Title', '$Story', '$Author', '$Date')";
?>
<h2>Submit News</h2>
<?php// echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<span class="error">* <?php echo $TitleErr;?></span>
Title: <input type="text" name="Title">
<span class="error">* <?php echo $AuthorErr;?></span>
Author: <input type="text" name="Author">
<span class="error">* <?php echo $DateErr;?></span>
Date: <input type="date" name="Date">
<input type="submit"><br>
<span class="error">* <?php echo $StoryErr;?></span>
Story: <br><textarea type="textarea" rows="40" cols="100" name="Story" method="post"></textarea>
</form>
</div>
<?php
//// escape variables for security
//$Title = mysqli_real_escape_string($con, $_POST['Title']);
//$Story = mysqli_real_escape_string($con, $_POST['Story']);
//$Author = mysqli_real_escape_string($con, $_POST['Author']);
//$Date = mysqli_real_escape_string($con, $_POST['Date']);
//Insert into database
?>
I'm going to hazard an answer. Main thing I see is you are using == as assignment and = as comparison. This is backwards.
$valid4 == true; should be $valid4 = true;
if ($valid1 = $valid2 = $valid3 = $valid4 = true) should be if ($valid1 == $valid2 == $valid3 == $valid4 == true) or not really, since it actually has to be:
if ($valid1==true && $valid2==true && $valid3==true && $valid4==true)
With assignment you can stack up the operator, but with boolean comparison, combine the compares with and (&&).
Just some advise, don't make pages submit to themselves. Make a separate page to handle the form from the one that displays the form. That way if you ever want to upgrade to using Ajax, its much easier. Also after doing a db update like this you always need to redirect to another page to prevent double submit (unless using ajax). The page doing the db update should not print anything out but just do the db update and redirect, unless there's a validation error.
Change your PHP to this:
if (isset($_POST['Title'],$_POST['Date'], $_POST['Author'], $_POST['Story'] )){
$con = mysqli_connect("localhost", "my_user", "my_password", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$title = $_POST['Title'];
$date = $_POST['Date'];
$author = $_POST['Author'];
$story = $_POST['Story'];
$query = "INSERT INTO Moderate (Title, Story, Author, Date)
VALUES (?, ?, ?, ?)"
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, $query)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ssss", $city);
/* execute query */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($con);
}
I cannot redirect to the page I want after even I enter correct recaptcha challenge and activation code. I am doubtful what is the problem in my php activation script. Can anybody check what is the error in my script?
Here is my script:
<?php
require_once('recaptchalib.php');
$privatekey = "6LfTwvMSAAAAABt03yGb0_12rgLNrCDuoibU4gbh";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
$username = $_POST['username'];
$activation_code = $_POST['activation_code'];
$db_host = "server";
$db_name = "table";
$db_use = "user";
$db_pass = "pass";
$link = mysqli_connect($db_host, $db_use, $db_pass);
mysqli_select_db($link, $db_name);
$command = "UPDATE email_activation SET check_activation='$activation_code' WHERE username='$username' and activation='$activation_code'";
$result = mysqli_query($command);
if ($result) {
$query = "SELECT * FROM email_activation where username LIKE '%$username%' LIMIT 0 , 1 ";
$result = mysqli_query($query) OR die(mysqli_error());
while($row = mysqli_fetch_array($result))
{
$username = $row['username'];
$password = $row['password'];
$email = $row['email'];
$postcode = $row['postcode'];
$query = "INSERT INTO member (username, password, email, postcode) VALUES ('$username','$password','$email','$postcode')";
$result = mysqli_query($link, $query) OR die(mysqli_error());
if ($result) {
echo "Congratulations. Your membership has been activated redirecting...";
$_SESSION['user_logged'] = '1';
header("location:index.html");
}else{
echo ("Congratulations. Your membership has been activated but it's can't saved in database.");
header("location:index.html");
}
}
}else{
echo ("You've entered an invalid username / activation code – please retry");
header("location:activation-form.php");
}
}
?>
You cant use header('location: something.html'); after echoing data.
Header has to be called before anything is sent to the browser.
echo ("Congratulations. Your membership has been activated but it's can't saved in database.");
header("location:index.html");
I advise passing the error on to the next page...
header("location: index.html?err=dberr");
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.