Comments not adding when submit button is pressed with PHP - php

Practising PHP by creating a very simple page that has a picture and the user can comment on it. I pretty much have everything down except adding the comment to the table within the database. I have it so I get an alert when the comment either gets added to the table or it does not go through. As far as I can tell, the code looks good but I could be wrong.
Here is the PHP file with the config info
<?php
$servername = "localhost";
$user = "user1";
$password = "";
$dbname = "comment_section";
//Create connection to database
$conn = mysqli_connect($servername, $user, $password, $dbname);
if(!conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE comment_list (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
nid VARCHAR(128) NOT NULL,
comments TEXT NOT NULL,
date datetime NOT NULL
)";
if (mysqli_query($conn, $sql)) {
echo "Table comment_list created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
And here is my index file
<?php
include 'comments.php';
error_reporting(0);
if (isset($_POST['submit'])) {
$name = $_POST['nid'];
$comment = $_POST['comments'];
$sql = "INSERT INTO comment_list (nid, comments)
VALUES ('$name', '$comment')";
$result = mysqli_query($conn, $sql);
if ($result) {
echo "<script>alert('Comment added')</script>";
} else {
echo "<script>alert('Comment not added')</script>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<!-- CSS, JS, and PHP files goes here -->
<link rel="stylesheet" href="style.css">
<!-- javascript code goes here -->
<!-- end of js code -->
</head>
<body>
<!-- Intro to what the site is about, possible pages to include comments -->
<header>
<h1></h1>
<nav>
<ul>
</ul>
</nav>
</header>
<!-- Image with comment section -->
<article>
<img src="images/IMG_1560.JPG" alt="" ">
<div class="wrapper">
<form action="" method="POST" class="form">
<div class="name">
<label for="name">Name</label>
<input type="text" name="nid" id="nid" placeholder="Name" required>
</div> <!-- End div class name -->
<div class="comment">
<label for="comment">Comment</label>
<textarea name="comments" id="comments" placeholder="Comment" required></textarea>
</div> <!-- End of div for textarea -->
<div class="but">
<button name="submit" class="btn">Post Comment</button>
</div>
</form>
<?php
$sql = "SELECT * FROM comment_list";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<?php echo $row['nid']; ?>
<p><?php echo $row['comments']; ?></p>
<?php
}
}
?>
</div>
</article>
<footer>
<p></p>
</footer>
</body>
</html>
Now every time I try to test and click on the submit button. I get an alert and the Comment Not Added pops up. Am I missing something? I also want it to show under the form whenever a user has left a comment. I know I can use Ajax without having to refresh the page, but I at least want to get the comment into the db/table and displayed under the form.

Related

fail to create account via php on mysql database

I´m having trouble creating data onto a MySQL database via a php that I created in order to be able to create an account on a website I´m making I have the following php files that take care of the process (linked below), I have been looking to these lines of code for hours and I'm not able to figure out what is wrong with it ....
signup.php
<?php
require 'db.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>AlojArt Reservas</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- styles -->
<link href="css/styles.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['login'])) { //user logging in
require 'login.php';
}
elseif (isset($_POST['register'])) { //user registering
require 'register.php';
}
}
?>
<body class="login-bg">
<div class="header">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-------------------- Logo -------------------->
<div class="logo">
<h1>AlojArt Reservas</h1>
</div>
</div>
</div>
</div>
</div>
<div class="page-content container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-wrapper">
<div id="register">
<div class="box">
<form action="signup.php" method="post" autocomplete="off">
<div class="content-wrap">
<h6>Criar conta</h6>
<input class="form-control" type="text" placeholder="Nome" name="nome_titular">
<input class="form-control" type="text" placeholder="Nome de utilizador " name="username">
<input class="form-control" type="password" placeholder="Palavra-passe" name="password">
<input class="form-control" type="email" placeholder="Endereço de e-mail" name="email">
<div class="action">
<button class="btn btn-primary btn-lg" name="register" />Criar conta</button>
</div>
</div>
</form>
</div>
</div>
<div class="already">
<div id="login">
<p>Já tem conta?</p>
Iniciar sessão
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="js/custom.js"></script>
</body>
</html>
register.php
<?php
require 'db.php';
session_start();
$_SESSION['nome_titular'] = $_POST['nome_titular'];
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['email'] = $_POST['email'];
// Escape all $_POST variables to protect against SQL injections
$nome_titular = $mysqli->escape_string($_POST['nome_titular']);
$username = $mysqli->escape_string($_POST['username']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM Utilizador WHERE email='$email'") or die($mysqli->error());
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'O utilizador jรก existe!';
header("location: error.php");
}
else { // User doesn't already exist in a database, proceed...
$sql = "INSERT INTO Utilizador (nome_titular, username, email, password)"
. "VALUES ('$nome_titular','$username','$email','$password')";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['logged_in'] = true;
header("location: dashboard.php");
}
else {
$_SESSION['message'] = "O registo falhou!";
header("location: error.php");
}
}
?>
EDIT: added db.php
db.php
<?php
/* Database connection settings */
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'projeto2_dcw';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
?>
I see there is no space ' ' before VALUES, this would cause failure of SQL.
Change your SQL to
$sql = "INSERT INTO Utilizador (nome_titular, username, email, password)"
. " VALUES ('$nome_titular','$username','$email','$password')";
If you still getting unexpected result, then please put following code to else get the error and comment out everything else.
printf("Error: %s\n", $mysqli->error);
==Update==
"Error: Duplicate entry '0' for key 'PRIMARY"
It refers to primary key constraint violation, in other word, you are trying to insert new value 0, which is already present in same column. Since, primary key doesn't allow duplicate. It is failing and falling to else block. To correct this issue, you need to make sure, you don't have duplicate entry for column which has primary key.
I see there is no connection for your page thats why it gets redirected to error.php change your db connection to this
<?php
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'projeto2_dcw';
$con = mysqli_connect("$host,$user,$pass,$db") or die($mysqli->error);
mysqli_select_db($con,"your db name");
?>
in the form change button
<button type="submit" class="btn btn-primary btn-lg" name="register" />Criar conta
ALTER TABLE Your table name
ADD PRIMARY KEY (ID);

checking result from select query then compare to current value if available then should not insert

I am saving latlong with the help of geolocation api into mysql db but problem is same latlong are inserted in database.I am trying to check last row of my mysql table and then comparing with current latlong if both are same,it should not be executed.Please help me to get this..Thanks in advance.
$latitude = 19.1579;
$longitude = 72.9935;
$address = airoli;
$sql = "SELECT latitude FROM tracklatlong ORDER BY id DESC LIMIT 1";
$result = mysqli_query($sql, $conn);
$row = mysqli_fetch_array($result);
$currentlat = $_row["latitude"];
if($currentlat != $latitude){
$query = "INSERT INTO `tracklatlong` (latitude, longitude,address) VALUES ('$latitude','$longitude','$address')";
if($conn->query($query) === TRUE){
echo "success";
}
else{
echo "failed";
}
}
else{
echo"Already exists";
}
As understood you need to check weather the latitute or longitute is in database Table insert it only if found false.
I am using PHP Object oriented with mysqli prepared statements.
This code returns false only when both latitute and longitute are same.
if you want output to return false were any one matchs the output than just add OR operator in SELECT query.
Here is the table image with data
Here is html code :index.php
<?php
include('co_ordinate.php');
$newcoordinate = new co_ordinate();
?>
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-6 col-md-offset-3" style="margin-top:100px;">
<form action="" method="post">
<div class="form-group">
<i>Add Latitute</i>
<input type="text" name="latitute" class="form-control">
</div>
<div class="form-group">
<i>Add Longitute</i>
<input type="text" name="longitute" class="form-control">
</div>
<div class="form-group">
<input type="submit" name="addcoordinate" class="btn btn-primary">
</div>
</form>
<?php
if(isset($_POST['addcoordinate'])){
$latitude = $_POST['latitute'];
$longitute = $_POST['longitute'];
$newcoordinate->getCo_ordinates($latitude,$longitute);
}
?>
</div>
</body>
</html>
Here is the class file :co_ordinate.php
<?php
class co_ordinate{
private $link;
function __construct(){
$this->link = new mysqli ('localhost','root','','example');
if(mysqli_connect_errno()){
die("connection Failed".mysqli_connect_errno());
}
}
function getCo_ordinates($latitude,$longitute){
$sql = $this->link->stmt_init();
if($sql->prepare("SELECT latitude,longitude FROM tracklatlong WHERE latitude=? AND longitude= ?")){
$sql->bind_param('dd',$latitude,$longitute);
$sql->execute();
$sql->store_result();
if($sql->num_rows > 0){
echo "The Co-Ordinates Already Exists";
}
else
{
$query = $this->link->stmt_init();
if($query->prepare("INSERT INTO tracklatlong (latitude,longitude) VALUES (?,?)")){
$query->bind_param('dd',$latitude,$longitute);
$query->execute();
echo "The Co-Ordinates Inserted Successfully";
}
}
}
else
{
echo $this->link->error;
}
}
}
?>

Update not working PHP MYSQL CRUD

I have this PHP code, when I try to click the yes button and check the database.The value remains the same. Is there something I am doing wrong? I also check my SQL query and it seems to be working fine but when I incorporate it in the php code . It is not working anymore?
<?php
require 'database.php';
$id = 0;
if ( !empty($_GET['gpx_field_id'])) {
$id = $_REQUEST['gpx_field_id'];
}
if ( !empty($_POST)) {
// keep track post values
$id = $_POST['gpx_field_id'];
// delete data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE field_info SET verify = '1' WHERE gpx_field_id = ? ";
$q = $pdo->prepare($sql);
$q->execute(array($id));
Database::disconnect();
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="assets/bootsrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Verify a Field</h3>
</div>
<form class="form-horizontal" action="verify.php" method="post">
<input type="hidden" name="gpx_field_id" value="<?php echo $id;?>"/>
<p class="alert alert-error">Are you sure to verify this field ?</p>
<div class="form-actions">
<button type="submit" class="btn btn-danger">Yes</button>
<a class="btn btn-danger" href="index.php">No</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
Here I assume your query is working fine so
Please change your php code as below...
<?php
require 'database.php';
$id = 0;
if ( !empty($_GET['gpx_field_id'])) {
$id = $_REQUEST['gpx_field_id'];
}
if ( !empty($_POST)) {
try {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE field_info SET verify = '1' WHERE gpx_field_id IN :id ";
$q = $pdo->prepare($sql);
$q->execute(array($id));
Database::disconnect();
header("Location: index.php");
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
Hope it will help you.
You specify $id = 0 at the top, but it is never updated to some 'real' value. Therefore, the form is populated with
<input type="hidden" name="gpx_field_id" value="0"/>
and thus gpx_field_id always remains 0. Then, your query will update all rows with WHERE gpx_field_id = 0. Most probably, those rows will not exist...
You do need to get a proper value for $id before you insert it in the form.
On a side-note, since you are using html5 (<!DOCTYPE html>), the closing tag for input should be omitted. Write instead: <input type="hidden" ... >, leaving out the forward slash, just as you did with the meta and link tags in the head section.

PHP POST and GET in same statement

I've found similar questions, but have been unable to tie them into my example. I am very new to PHP and completely self teaching.
At present I have a form for entering a new customer. In that form I want the user to be able to select an existing DB item (business) and insert that BusinessID into the CUSTOMER table. My problem is that I can GET the BusinessID, but then I can't POST that same ID with the other field inputs. Code below
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>New Contact</title>
<!--Declare CSS and JavaScript-->
<link rel="stylesheet" type="text/css" href="RealtyCRM_Style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery.resmenu.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
$('.toresponsive').ReSmenu();
});
</script>
<!--Begin Header Code-->
<!--Begin Header Code-->
<div class="BodyHeader">
<div>
</div>
</div>
<!--Begin Menu Code-->
<div class="menu_container" style="position:relative; z-index:11;">
<ul class="toresponsive">
<li>Log In</li>
<li>Contact</li>
<li>News</li>
<li class="current-menu-item">Dashboard
<ul>
<li>Add New Data</li>
<li>Update Data</li>
<li>Search</li>
<li>Report</li>
<li>Admin Page</li>
<li>Log Interaction</li>
</ul>
</li>
</ul>
</div>
<br>
<!--Begin Dashboard Buttons Code-->
<div class="DashboardButtonsTop">
<h1 class="centeredDashBoardButtonInactive">New Retailer</h1>
<h1 class="centeredDashBoardButton">New Contact</h1>
<h1 class="centeredDashBoardButtonInactive">New Property</h1>
</div>
<hr style="width:700px; height:5px;">
<br>
<br>
<!--END Dashboard Buttons Code-->
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost';
$dbuser = 'leasingl_dbwrite';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$contactFirstName = addslashes ($_POST['contactFirstName']);
$contactLastName = addslashes ($_POST['contactLastName']);
}
else
{
$contactFirstName = $_POST['contactFirstName'];
$contactLastName = $_POST['contactLastName'];
}
$contactPhoneNumber = $_POST['contactPhoneNumber'];
$contactEmail = $_POST['contactEmail'];
$Business = $_POST['BusinessID'];
$sql = "INSERT INTO Contact ". "(ContactFName,ContactLName, ContactMobilePhone, contactEmail, BusinessID, CreatedDate) ". "VALUES('$contactFirstName','$contactLastName','$contactPhoneNumber', '$contactEmail', '$Business', NOW())";
mysql_select_db('applicationDatabase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "<div style='text-align:center;'>Entered data successfully\n</div>";
echo "<br><div><a href='contactdataentry.php' class='redirectButton'>Add More Contacts</a>\n</div>";
echo "<br><div><a href='dashboard.php' class='redirectButton'>Return to Dashboard</a></div>";
mysql_close($conn);
}
else
{
?>
<div class="Form_container">
<form method="post" action="<?php $_PHP_SELF ?>">
Contact First Name<br>
<input class="largeInput" type="text" name="contactFirstName" ID="contactFirstName"><br>
Contact Last Name<br>
<input class="largeInput" type="text" name="contactLastName" ID="contactLastName"><br>
Contact Phone Number<br>
<input class="largeInput" type="text" name="contactPhoneNumber" placeholder="### - ### - ####" ID="contactPhoneNumber"><br>
Contact Email<br>
<input class="largeInput" type="text" name="contactEmail"><br>
Business<br>
<?php
$servername = "localhost";
$username = "leasingl_dbread";
$password = "password";
$dbname = "applicationDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT RetailerID, RetailerName FROM Retailer ORDER BY RetailerName DESC";
$result = $conn->query($sql);
?>
<select style='text-align:center;' class='largeInput' name='Business' ID='Business'>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='". $row["RetailerID"]. "'>" . $row["RetailerName"]. " - " . $row["RetailerID"]. "</option><br><br>";
}
} else {
echo "0 results";
}
?>
</select><br><br>
<?php
$conn->close();
?>
<input name="add" type="submit" id="add" value="Add Contact" class="button">
</form>
<br>
<hr style="width:400px; height:10px;">
</div>
<?php
}
?>
</body>
</html>'
So being able to insert the value from my drop down is the main issue. Additionally, I'm sure there is unnecessary / incorrect code in what I posted, I've been piecing together examples one at a time.
Thank you for all the help, if I can get this working I can have a functioning basic version of my application
EDIT
I have successfully prepopulated my drop down, and the user then chooses from that list. I want to pass that choice via my INSERT statement. I worry that the two different CONNECTIONS which I establish are part of the reason my INSERT won't recognize $Business
It appears you are referring to GET in a confusing way. In PHP there is $_GET and $_POST variables, and when you mention GET in all-caps, in implies you are using $_GET - which in fact you are not.
The solution - as I understand the question - is actually fairly straightforward.
Inside your form, add a hidden input that stores (and then passes) the BusinessID variable, like so:
<input type="hidden" name="BusinessID" value="<?php echo $Business; ?>">
As you mention you are just learning, here's some additional tips:
Name your variables consistently throughout. If the name of the database column is BusinessID, then name your variable $businessID" and your inputBusinessID".
Kudos to you for good indenting / formatting! That will save you gobs of time when troubleshooting / reading your own code!
EDIT
If what you are trying to do is pre-select the record in the dropdown, then alter your loop like so:
while($row = $result->fetch_assoc()) {
// Note: I've removed the <br> tags here, they don't belong in a select dropdown
echo "<option value='". $row["RetailerID"]. "'";
// If the ID matches, make this the selected option
// NOTE: Per my tip above, I'd strongly recommend changing the variable name $Business to match the field name - $RetailerID in this case
echo ($row['RetailerID'] == $Business) ? ' selected' : '';
echo ">" . $row["RetailerName"]. " - " . $row["RetailerID"]. "</option>";
}

Echoed text showing up in wrong place

I'm creating a page with PHP for a class and when I echo things it shows up in the wrong place.
Here is my HTML page
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<table>
<tr>
<td><span>First name:</span></td>
<td><input type="text" name="firstname"></td>
</tr>
<tr>
<td><span>Last name:</span></td>
<td><input type="text" name="lastname"></td>
</tr>
<tr>
<td><span>Age:</span></td>
<td><input type="number" name="age"></td>
</tr>
</table>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
Here is my PHP page:
<?php
$con = mysql_connect("localhost","USERNAME","PASSWORD");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
mysql_select_db("a7068104_world") or die("Cannot connect to database");
header("refresh:1.5; url=NamesAction.php");
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$fullname = mysql_real_escape_string($_POST['firstname'] . " " . $_POST['lastname']);
$age = mysql_real_escape_string($_POST['age']);
$query = "SELECT * FROM names_1 WHERE fullname='$fullname'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname, lastname, fullname, age) VALUES('$firstname', '$lastname', '$fullname', '$age')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else{
echo "Your name couldn't be added to the database!";
}
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
When I echo stuff in my PHP page it shows up at the very top of the frame that it's in right above the
<div id="main">
I want the echoed text to go in the very bottom of the
<div id="main">
Is there any way that I can do that? I appreciate your help!
Thanks,
Leonardude
Your issue is that you are echo'ing the message before you supply your HTML.
Which is evident here:
if($result) {
echo "Your name was successfully added to the database!";
}
else{
echo "Your name couldn't be added to the database!";
}
Because PHP is a server-side language and HTML is client-side, the PHP will process well before the HTML, meaning it will echo before the page is displayed. Hence the issue where it is before your <div id="main"></div>.
A way around this is by setting a variable
if($result) {
$var = "Your name was successfully added to the database!";
}
else{
$var = "Your name couldn't be added to the database!";
}
And somewhere in your <div id="main"></div> you could do something like the following:
<div id="main">
<?php
if(isset($var) && !empty($var)) {
echo $var;
}
?>
</div>

Categories