I was wondering if there were any kind people out there who would be able to help me with my php conundrum! Im very very new to php and I can't quite understand how to add a comment section that is functional. I have made a database table (named 'comments') to store all of the comments that users will submit. I am not sure of these things:
1. how to connect the comment section (on php page - home.php) to my database table (comments)
2. how to make the comments that people post be posted onto the the same page - home.php
I have done something wrong as now when I type in the URL this error comes up
Parse error: syntax error, unexpected '{', expecting '(' in .../home.php on line 34
Anyway I hope someone can help me!
Thanks
<?php
session_start();
if (!isset($_SESSION['logged'])){
$_SESSION = array();
session_destroy();
header('location: home_start.php'); //your login form
require_once("functions.php");
include_once("home_start.php");
require_once("db_connect.php");
}
//EXISTING DATABASE CONNECTION CODE
//if (!$db_server){
//die("Unable to connect to MySQL: " . mysqli_connect_error($db_server));
}else{ $ db_status = "not connected";
//NEW SUBMISSION HANDLING CODE HERE
//if(trim($_POST['submit']) == "Submit"){
//}//EXISTING CODE (to create the options list) HERE...
//}
require_once('recaptcha/recaptchalib.php');
$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) {
$message = "The reCAPTCHA wasn't entered correctly. Go back and try it again (reCAPTCHA said: " . $resp->error . ")";
} else {
// ADD YOUR CODE HERE to handle a successful ReCAPTCHA submission
// e.g. Validate the data
$unsafe_name = $_POST['fullname'];
}
$message .= "Thanks for your input $unsafe_name !";
echo $message;
if {
$bedrooms = $_POST['year'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
else ($comment != "") {
$query2 = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query2) or
die("Insert failed: " . mysqli_error($db_server));
$message = "Thanks for your comment";
}
$query3 = "SELECT * FROM comments";
$result3 = mysqli_query($db_server, $query3);
while($array = mysqli_fetch_array($result3)){
$comments = date('d/m/Y', strtotime($array['commDate'])) . "<p>" . $array['comment'] . "</p><br/>";
}
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="home.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
</head>
<body>
<div id="middle">
<h2><strong>HELLO!</strong></h2>
<h2>Welcome to <strong>Cosy Cribs</strong> website!</h2>
<p>This website combines all the possible lettings available to YOU from the most prefered letting companies in the great city of Leeds!</p>
<p>It was recognised that when students attempt to let a house for the next year, there were far too many different websites and companies visit; making the whole ordeal of finding a house more stressful then needs be!</p>
<p>We, at <strong>Cosy Cribs</strong>, decided that your lives needed to be made easier, and so we announce a website that provides you with all of the lettings from these different companies - all on one website - and links to the house you like.</p>
<h2>ENJOY!</h2>
</div>
<form id="comments" action="home.php" method="post">
<select name="comments">
</select>
<h1>Do you have a comment on preferred company or number of bedrooms?</h1>
Comment: <textarea rows="2" cols="30" name="comment"></textarea>
<?php echo $recaptcha_form; ?>
<input type="submit" id="submit" name="submit" value="Submit form" />
</form>
</body>
</html>
Your below statement is syntactically incorrect,
if {
$bedrooms = $_POST['year'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
else ($comment != "") {
Should be,
if (isset($comment) && $comment == '') {
$bedrooms = $_POST['year'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
}
else {
Related
this is my first php code and it is full of problems probably :)
I want to register information of people visiting my website. My main problem is that FARSI words in sql are not registered right and it is showing wrong characters.
I tried to use N for making it unicode but it didn't work for me. Maybe I'm using it wrong.
Also I tried give everyone a unique ID but I could not figure how.
My sql collation for FARSI parts are utf8 persian ci. I am using phpmy admin and I tried to make nvarchar in it but it only offers varchar.
This is my first question and first php code so please forgive me If it is too basic.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<?php
$name = $_POST["name"];
$familyname = $_POST["familyname"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$pass = $_POST["pass"];
$pass2 = $_POST["pass2"];
$id = 100;
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
echo("$email صحیح نمی باشد");
} else {
$con = mysqli_connect("localhost","","","register");
$name = mysqli_real_escape_string($con, $_POST['name']);
$familyname = mysqli_real_escape_string($con, $_POST['familyname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$phone = mysqli_real_escape_string($con, $_POST['phone']);
$pass = mysqli_real_escape_string($con, $_POST['pass']);
$pass2 = mysqli_real_escape_string($con, $_POST['pass2']);
mysqli_query($con,"INSERT INTO users (`name17`, `familyname17`, `email17`, `phone17`, `pass17`, `id17`) VALUES ('$name', '$familyname', '$email', '$phone', '$pass', '$id')");
$result = mysqli_query($con,"select * from users where email17 ='$email' and pass17 = '$pass' and familyname17 = '$familyname'" )
or die("faild to query database".mysql_error());
$row = mysqli_fetch_array($result,MYSQLI_BOTH);
if (empty($name) || empty($familyname) || empty($email) || empty($phone) || empty($pass) || empty($pass2)) {
echo "لطفا اطلاعات را بطور کامل وارد فرمایید";
}
else {
if ($row['email17']==$email && $row['pass17'] == $pass2){
echo "<body style='direction: rtl !important;'>";
echo "<b>".$row['name17']." <b>";
echo "عزیز. خوش آمدید<br> ";
echo '<img src="images/takhfif.jpg" alt="تخفیف" />';
} else {
echo "خطا در ثبت نام.لطفا دوباره تلاش کنید";
}
}
}
?>
</body>
</html>
make sure you are using utf8 . change your database collation to utf8_general . this should work .
I had the same problem when i was learning php .
Hello everyone and thanks for the answers.
if found the solution to my problem. for those who have the same problem, Set collation to utf8 general or unicode. But you must set your input to utf8 also. I inserted the following code to do so.
I hope this helps and if you had problemsplease ask.
I use mysqli but normal mysql connection is pretty much the same.
$con = mysqli_connect("localhost","db_user","db_pass","db_name");
after connecting to db use this code:
mysqli_set_charset($con,"utf8");
My site is an admin login site, therefore users cannot register. However they can post comments to the site. I have delete buttons on the comments but didn't realise that anybody can then delete anybodies comments. How can I change this so when the admin is logged in they are able to delete inappropriate comments (if any) and get rid of the delete button from the general public.
This is my Comment.php code with the delete button function in there:
<?php
session_start();
require_once 'templates/open.php';
require_once 'connect.php';
require_once 'functions/cleanstring.php';
require_once 'functions/encrypt.php';
?>
Another code file:
<?php
$db_hostname = 'localhost';
$db_database = 'cs12e2g_MyFirstDB'; //'Your database name'
$db_username = 'cs12e2g_DBuser'; //'your username';
$db_password = 'vtjppqs7'; //'Your password';
$db_status = 'not initialised';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
}
// Includes and variables always required
require_once 'recaptcha/recaptchalib.php';
require_once 'functions/cleanstring.php';
$privatekey = "6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
$publickey = "6Lem4-gSAAAAAMHLAVbieIknMtUZo71ZKzzCkoFN";
mysqli_select_db($db_server, $db_database);
$str_message = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
if(isset($_GET['delete'])){
$deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter=mysqli_query($db_server, $deleteq);
IF($deleter){
echo"<p>That message was deleted!</p>";}}
//Test whether form has been submitted
if(trim($_POST['submit']) == "Submit"){
//Handle submission
$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
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
again.
(reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if($comment != ""){
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " .
mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
}else{
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) );
while($row = mysqli_fetch_array($result)){
$ID= $row['ID'];
$str_result .= "<p><em>Comment $j (" . $row['commDate'] .
")</em><br /> " .$row['comment'] . "</p>
<a href ='commentnow.php?delete=$ID
'>Delete</a><hr />";
}
mysqli_free_result($result);
}
?>
<h1>What do you think?</h1>
<p><h5>Did you find everything you wanted? Please comment below:<h5></p>
<form action="commentnow.php" method="post">
<textarea rows="10" cols="50" name="comment"></textarea><br />
<?php echo recaptcha_get_html($publickey); ?>
<input type="submit" name="submit" value="Submit" />
</form>
<span style="color:#FF0000;">
<?php echo $str_message; ?></span>
<hr />
<h2>Comments:</h2>
<?php echo $str_result; ?>
</div>
<?php
require_once 'templates/close.php';
?>
I have a members.php page which corresponds to when the admin logs in (they are the only ones that can access this page) would the delete button code have to go in here? so they are the only ones that can use the function? If so where would it go, and how?
Restrict the delete button to show only for the admin. Also this would mean that you somehow identify if the logged in user is an admin.
if ($is_admin) {
// Code to display button
}
Also in the backend check if the logged in user is admin
if ($is_admin) {
// Code to delete comment
delete_comment();
}
and you welcome to php.
You have that identify the users that enter in your application.
Using database or arrays or files or variables etc etc.
If permission is equal to admin or editor (For example) allow delete.
For example
if( $login == 'admin' ){
// Allow action
}
My you understand?
(My English is bad, sorry)
I can't seem to correct my php error having looked at their answers and corrections. This is the error I get when the page is refreshed on the internet:
mysqli_query() expects parameter 1 to be mysqli, null given…
<?php
session_start();
if (!isset($_SESSION['logged'])){
$_SESSION = array();
header('location: home_start.php'); //your login form
require_once("functions.php");
include_once("home_start.php");
$db_hostname = 'xxxx';
$db_database = 'xxx'; //'Your database name'
$db_username = 'xxx'; //'your username';
$db_password = 'xxx'; //'Your password';
$db_status = 'not initialised';
$str_result = ' ';
$str_options = ' ';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
$db_select = mysqli_select_db($db_server, $db_database);
}
//EXISTING DATABASE CONNECTION CODE
//if (!$db_server){
//die("Unable to connect to MySQL: " . mysqli_connect_error($db_server)); }else{ $db_status = "not connected";
//NEW SUBMISSION HANDLING CODE HERE
//if(trim($_POST['submit']) == "Submit"){
//}//EXISTING CODE (to create the options list) HERE...
//}
//require_once('recaptcha/recaptchalib.php');
//$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) {
//$message = "The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")";
//} else {
// ADD YOUR CODE HERE to handle a successful ReCAPTCHA submission // e.g. Validate the data
//$unsafe_name = $_POST['fullname'];
//}
//$message .= "Thanks for your input $unsafe_name !";
//echo $message;
if (isset($comment) && $comment == '') {
$bedrooms = $_POST['bedrooms'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
}
else {
$query1 = "INSERT INTO comments (comment) VALUES ('$comment')";
$result = mysqli_query($db_server, $query1); if(!result){ die("Insert failed: " . mysqli_error($db_server));
}
$message = "Thanks for your comment";
}
function getPosts(mysqli $db_select){
$query1 = "SELECT * FROM comments";
$result1 = mysqli_query($db_server, $query1);
while($array = mysqli_fetch_array($result1)){
$comments = date('d/m/Y', strtotime($array['commDate'])) . "<p>" . $array['comment'] . "</p><br/>";
}
}
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="home.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
</head>
<body>
<div id="middle">
<h2><strong>HELLO!</strong></h2>
<h2>Welcome to <strong>Cosy Cribs</strong> website!</h2>
<p>This website combines all the possible lettings available to YOU from the most prefered letting companies in the great city of Leeds!</p>
<p>It was recognised that when students attempt to let a house for the next year, there were far too many different websites and companies visit; making the whole ordeal of finding a house more stressful then needs be!</p>
<p>We, at <strong>Cosy Cribs</strong>, decided that your lives needed to be made easier, and so we announce a website that provides you with all of the lettings from these different companies - all on one website - and links to the house you like.</p>
<h2>ENJOY!</h2>
</div>
<form id="comments" action="home.php" method="post">
<select name="comments">
</select>
<h1>Do you have a comment on preferred company or number of bedrooms?</h1>
Comment: <textarea rows="2" cols="30" name="comment"></textarea>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Seems like you are overwriting your $db_server on the line that reads:
$db_server = mysqli_query($db_server, $query1) or
die("Insert failed: " . mysqli_error($db_server));
So you should change that to be another variable like $result1:
$result1 = mysqli_query($db_server, $query1) or
die("Insert failed: " . mysqli_error($db_server));
That said, are you actually connecting via $db_server anywhere else in your code? Look out for errors similar to what I just pointed out.
your $db_server is null which should a valid mysqli instance. this indicates either database connection failed or you didn't initialize $db_server or you overwritten it and looks like last option is true.
$db_server = mysqli_query($db_server, $query1)
this overwrites $db_server.
Insted of $db_server use $db_select. This may work as your $db_server variable does not have a connection to database. Its just a connection to server.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I'm new to PHP, and I tried to research this question but maybe I'm not asking right... I can tell from other posts/instructionals that I can not user header() or setcookie() after printing out HTML...
I commented out the header "redirects" - is there an alternative to this that I can put after HTML?
It's the setcookies that are failing at the moment:
what am I not seeing? I keep getting errors but my HTML is after the PHP:
if (!isset($_COOKIE["user"])) {
$sUserIdentity = $_POST["userIdentity"];
//username is not accepted as a get value
$sPassword = $_POST["password"];
$sEmail = $_POST["email"];
$cnn= odbc_connect("Driver={SQL Server};Server=$server;Database=$dbI", $user, $password);
//check to see if email account or username already used
$sql2 = "select id from i_user where email = '" . $sEmail . "' or username ='" . $sUserIdentity . "'";
//echo $sql2 ."<br>";
$result = odbc_exec($cnn, $sql2);
$id = odbc_result($result,"id");
if ($id == ''){
$cnnCreate = odbc_connect("Driver={SQL Server};Server=$server;Database=$dbI", $user, $password);
$sqlCreate = "insert into i_user (username,email,salt,active) values ";
$sqlCreate .= "(";
$sqlCreate .= "'" . $sUserIdentity . "',";
$sqlCreate .= "'" . $sEmail . "',";
$rsCreate = odbc_exec($cnnCreate, $sqlCreate);
$sql2 = "select * from i_user where email = '" . $sEmail . "' and username ='" . $sUserIdentity . "'";
//echo $sql2 ."<br>";
$result = odbc_exec($cnn, $sql2);
$expire=time()+60*60*24*30;
setcookie("uid", odbc_result($result,"id"), $expire);
setcookie("user", odbc_result($result,"username"), $expire);
if ($rsCreate){
$sMsg = "congratulations " . $_COOKIE["user"] . " and welcome ";
}
else {
$sMsg = "There was an error with the query";
}
}else{
$sMsg = "User " . $id . " already in DB";
//header('Location: ../fec/createuser.php?error=id');
}
}
//echo $sqlCreate;
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>User Form</title>
<script type="text/javascript" src="../js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.10.2.custom.min.js"></script>
<link rel="stylesheet" href="../css/styles.css" type="text/css">
<style>
</style>
</head>
<body>
</body>
</html>
Make sure <?php is at the very beginning of the file, with no blank lines before it. And you can't print or echo anything before calling setcookie().
Why don't you use output buffering?
<?php
ob_start();
?>
<html>
<body>
...
</body>
</html>
<?php
ob_end_flush();
?>
This will put any output into a buffer and you can modify header information as long as the buffer isn't flushed.
This will also avoid problems in case a PHP warning or error message was sent to output before you write to the header.
I have a form with PHP that saves a variable to a MySQL database. That form worked on a VPS, but when trying it on another VPS it gives an error when trying to write to the database when the field contains a ' character. So the same PHP code works on 1 VPS when the field contains a ' character, but not on the other VPS.
Here it works: http://www.zoekmachineoptimalisatie.us/test.php
and here (it's the other VPS) it gives an error: http://www.onzebruidsfotograaf.nl/test.php
My form:
<?php
$hostname = "localhost"; //host name
$dbname = "xxxxxxxx"; //database name
$username = "xxxxxxxx"; //username you use to login to php my admin
$password = "xxxxxxxx"; //password you use to login
$conn = new MySQLi($hostname, $username, $password, $dbname);
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Untitled Document</title>
</head>
<body>
<?php
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = "UPDATE test SET Title='$title' WHERE BookID = " . $bookid;
$conn->query($update) or die("Cannot update"); //update or error
}
?>
<?php
$bookid = 1;
$sql = "SELECT * FROM test WHERE BookID = '" . $bookid . "'";
$result = $conn->query($sql) or die(mysql_error());
$query = getenv(QUERY_STRING);
parse_str($query);
?>
<h2>Update Record <?php echo $bookid;?></h2>
<form action="" method="post">
<?php
while ($row = $result->fetch_assoc()) {
?>
<textarea name="updatetitle" cols="100" rows="30"><?php echo $row['Title']; ?></textarea>
<table border="0" cellspacing="10">
<tr>
<td><INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"></td>
</tr>
</table>
<?php
}
?>
</form>
<?php
if ($update) { //if the update worked
echo "<b>Update successful!</b>";
}
?>
</body>
</html>
An unescaped quote in your query will produce a syntax error. Instead of building the SQL fully your own, make use of SQL variables for your PHP variables with a Prepared Statement:
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = $conn->prepare('UPDATE test SET Title = ? WHERE BookID = ?;');
$update->bind_param('sd', $title, $bookid);
$update->execute();
}
One of your servers has Magic Quotes enabled and the other doesn't. Magic Quotes is now considered undesirable and is deprecated, it automatically escapes input. You should turn off Magic Quotes and use a parameterised query/prepared statement instead - then there is no need to escape anything and it prevents SQL Injection.
Paramterised queries are supported by the MySQLi and PDO APIs.
because the single quote breaks the query statement. In order to prevent from it or from SQL Injection you need to use PDO or MySQLI extension. For more infor, see the article below
How can I prevent SQL injection in PHP?