How to insert multiple ID's in one linked table? - php

I want to insert de EmployeeID and the KnowledgeID in Knowledgedetail. He creates the employee but does nothing in the Knowledgedetail. I'm there now no code, I have tried so many things but i have no idea.
As first in Addprofile.php you make the profile and at least you choose yoour knowledge.
My question is if a make a profile and choose the knowledge how get i de ID's in knowledgedetail.
Table 1
Employees: EmployeeID, Name, Establishment, E-Mail, Phonenumber, Photo, Description
Table 2
Knowledge: KnowledgeID, Knowledge
Table 3
Knowledgedetail: KnowledgedetailID, EmployeeID KnowledgeID
EmployeeID out Employees have a relation with EmployeeID out Knowledgedetail and
KnowledgeID out Knowledge have a relation with KnowledgeID out Knowledegedetail
Addprofile.php
<?php
include("connection.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Information System</title>
<link rel="stylesheet" type="text/css" href="css/test.css">
<meta charset ="utf-8">
<link rel='stylesheet' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/smoothness/jquery-ui.css' type='text/css' media='screen' />
<link rel='stylesheet' href='css/ui.multiselect.css' type='text/css' media='screen' />
<script src="../Informatiesysteem/js/jquery.min.js"></script>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js'></script>
<script type='text/javascript' src='../Informatiesysteem/js/ui.multiselect.js'></script>
<script type='text/javascript'>
jQuery(document).ready(function() {
jQuery("#selectitems").multiselect();
});
</script>
</head>
<body>
<div id="container">
<div id="logo"></div>
<div id="header">
<h1>Add Profile</h1>
</div>
<div id="menu">
</div>
<div id="content">
<?php
$result = mysql_query("select knowledgeid, knowledge from knowledge");
$items = array();
$selected = array();
while ($row = mysql_fetch_array($result)){
$id [] = $row [ 'knowlegdeid' ];
$items[] = $row[ 'knowledge' ];
}
//form processing
if (isset($_POST['selectitems'])) {
$selected = $_POST['selectitems'];
}
if (!empty($selected)) : print_r($selected); endif;
?>
<form enctype="multipart/form-data" id="my form" method="post" action="Addedprofile.php">
Name: <input type="text" name="name" /></br>
Establishment: <input type="text" name="establishment"/></br>
E-Mail: <input type="email" name="email"/></br>
Phonenumber: <input type="tel" name="phonenumber"/></br>
Photo: <input type="file" name="photo"/></br>
Description: <textarea rows="4" cols="50" name="description"></textarea></br>
Knowledge: <select name="selectitems[]" id="selectitems" multiple="multiple" style="width: 450px; height: 180px;">
<?php //first we add the list of selected items if any
foreach ($selected as $sel) { ?>
<option value="<?php echo $sel; ?>" selected="selected"><?php echo $id[$sel]; $items[$sel];?></option>
<?php } ?>
<?php foreach ($items as $i => $v) { //then insert all items, skipping those who were added above
if (in_array($d, $i, $selected)) : continue; endif; //skip ?>
<option value="<?php echo $d, $i; ?>"><?php echo $v; ?></option>
<?php } ?>
</select>
</br></br></br></br>
<input type="submit" name="add_profile" value="Add profile" />
</form>
</div>
</body>
</html>
Addedprofile.php
<!DOCTYPE html>
<html>
<meta http-equiv="refresh" content=";URL=Addprofile.php" />
</html>
<?php
include ("connection.php");
$Name = $_POST['name'];
$Establishment = $_POST['establishment'];
$Email = $_POST['email'];
$Phonenumber = $_POST['phonenumber'];
$Photo = $_POST['photo'];
$Description = $_POST['description'];
$sql = "INSERT INTO employees
(
name,
establishment,
email,
phonenumber,
photo,
description
)
VALUES ('". $Name ."', '". $Establishment ."', '". $Email ."', '". $Phonenumber ."', '". $Photo ."', '". $Description ."')";
$sqldetail = "INSERT INTO knowledgedetail
(
employeeid,
knowledgeid
)
VALUES .......................";
$add = mysql_query($sql);
if ($add === false){
echo 'Profile is not created';
}
else {
echo "Profile created";
}
echo '</br>';
$knowledge = mysql_query($sqldetail);
if ($add === false){
echo 'Knowledge is not added';
}
else {
echo "Knowledge added";
}
echo '</br>';
?>

Here's one thing that's wrong with your code:
$knowledge = mysql_query($sqldetail);
if ($add === false){
echo 'Knowledge is not added';
}
else {
echo "Knowledge added";
}
In the if statement, you should compare $knowledge and not $add. So, it should be:
$knowledge = mysql_query($sqldetail);
if ($knowledge === false){
echo 'Knowledge is not added';
}
else {
echo "Knowledge added";
}
Also, add a call to mysql_error() every time mysql_query() fails:
echo "MySQL ERROR: SQL = $sql -- Error=".mysql_error()";

Related

PHP Delete and Re-insert all data from the form in edit.php

I have tried to update data through edit page by deleting all of the existing data from the 'positions' table and then re-insert them. When I press the 'Save' button, the page redirects perfectly to index page, but when i view the profile I see that the 'positions' database is empty.
Plz help as I have been grinding on this problem for a week now.
Edit.php
<?php
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ( isset($_POST['first_name']) && isset($_POST['last_name'])
&& isset($_POST['email']) && isset($_POST['headline'])
&& isset($_POST['summary']) && isset($_POST['profile_id'])) {
// Data validation
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
if ( !isset($_POST['first_name']) || !isset($_POST['last_name'])
|| !isset($_POST['email']) || !isset($_POST['headline']) || !isset($_POST['summary'])) {
$_SESSION['failure'] = "All fields are required";
header("Location: edit.php?profile_id=". $_REQUEST["profile_id"]);
return;
}
}
else{
$_SESSION["failure"] = "Email address must have an # sign.";
header("Location: edit.php?profile_id=". $_REQUEST["profile_id"]);
return;
}
$sql = "UPDATE `profile` SET first_name = ?,
last_name = ?, email = ?,
headline = ?, summary=?
WHERE profile_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
$_POST['first_name'],
$_POST['last_name'],
$_POST['email'],
$_POST['headline'],
$_POST['summary'],
$_POST['profile_id']));
$profile_id = $_GET['profile_id'];
$stmt = $pdo->prepare("DELETE FROM `Position` WHERE `profile_id` = ?");
$stmt->execute(array($_GET['profile_id']));
$rank=1;
for($i=1; $i<=9; $i++) {
if ( ! isset($_POST['year'.$i]) ) continue;
if ( ! isset($_POST['desc'.$i]) ) continue;
$year = $_POST['year'.$i];
$desc = $_POST['desc'.$i];
$stmt = $pdo->prepare("INSERT INTO `position`
(`profile_id`, `rank`, `year`, `description`)
VALUES ( ?, ?, ?, ?)");
$stmt->execute(array($profile_id, $rank, $year, $desc));
$rank++;
}
$_SESSION["success"]="Record Added";
header("Location: index.php");
return;
}
$stmt = $pdo->prepare("SELECT `profile_id`, `first_name`, `last_name`, `email`, `headline`, `summary` FROM `profile` WHERE `profile_id` = ?");
$stmt->execute(array($_GET['profile_id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// Flash pattern
if ( isset($_SESSION['failure']) ) {
echo '<p style="color:red">'.$_SESSION['failure']."</p>\n";
unset($_SESSION['failure']);
}
$fname = htmlentities($row['first_name']);
$lname = htmlentities($row['last_name']);
$email = htmlentities($row['email']);
$headline = htmlentities($row['headline']);
$summary = htmlentities($row['summary']);
$profile_id = $row['profile_id'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Rounak Simlai</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h1>Editing profile for<?php echo" ".$_SESSION['name'];?></h1>
<form method="post">
<p>First Name:
<input type="text" name="first_name" value="<?php echo($fname); ?>" size="60"/></p>
<p>Last Name:
<input type="text" name="last_name" value="<?php echo($lname); ?>" size="40"/></p>
<p>Email:
<input type="text" name="email" value="<?php echo($email); ?>"/></p>
<p>Headline:<br>
<input type="text" name="headline" value="<?php echo($headline); ?>"/></p>
<p>Summary:<br/>
<textarea name="summary" rows="8" cols="80"> <?php echo($summary); ?> </textarea></p>
<input type="hidden" name="profile_id" value="<?php echo($profile_id); ?>">
<p>Position: <input type="submit" id="addPos" value="+">
<div id="position_fields">
<?php
$stmt = $pdo->prepare("SELECT * FROM `position` WHERE profile_id = ?");
$stmt->execute(array($_GET['profile_id']));
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row){
$year=$row['year'];
$desc=$row['description'];
$countPos = 1;
echo"<div id='position'".$countPos.">";
echo"<p> Year: <input type='text' name=\"year ".$countPos."\" value='".$year."' /> ";
echo"<input type=\"button\" value=\"-\" onclick=\"$(\'#position'+countPos+'\').remove();return false;\"></p> ";
echo"<textarea name=\"desc".$countPos."' rows=\"8\" cols=\"80\" >$desc</textarea>";
echo"</div>";
$countPos++;
}
?>
</div>
</p>
<p>
<input type="submit" id="submit" value="Save"/>
Cancel</p>
</form>
</div>
<script>
countPos = 1;
$(document).ready(function(){
window.console && console.log('Document ready called');
$('#addPos').click(function(event){
event.preventDefault();
if ( countPos >= 9 ) {
alert("Maximum of nine position entries exceeded");
return;
}
countPos++;
window.console && console.log("Adding position "+countPos);
$('#position_fields').append(
'<div id="position'+countPos+'"> \
<p>Year: <input type="text" name="year'+countPos+'" value="" /> \
<input type="button" value="-" \
onclick="$(\'#position'+countPos+'\').remove();return false;"></p> \
<textarea name="desc'+countPos+'" rows="8" cols="80"></textarea>\
</div>');
});
});
</script>
</body>
</html>
VIEW.PHP
<?php
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt= $pdo->prepare("SELECT * FROM profile WHERE profile_id = ?");
$stmt->execute(array($_GET['profile_id']));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$fname=htmlentities($row['first_name']);
$lname=htmlentities($row['last_name']);
$email=htmlentities($row['email']);
$headline=htmlentities($row['headline']);
$summary=htmlentities($row['summary']);
$profile_id=htmlentities($row['profile_id']);
?>
<!DOCTYPE html>
<html>
<head>
<title>Rounak Simlai</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h1>Profile information</h1>
<form method="post">
<p>First Name: <?php echo(" ".$fname); ?></p>
<p>Last Name: <?php echo(" ".$lname); ?> </p>
<p>Email: <?php echo(" ".$email); ?> </p>
<p>Headline: <?php echo(" ".$headline); ?> <br/></p>
<p>Summary: <?php echo(" ".$summary); ?> <br/><p>
<input type="hidden" name="profile_id" value="<?= $profile_id ?>">
</p>
<p>Position</p><ul>
<?php
$stmt= $pdo->prepare("SELECT * FROM position WHERE profile_id = ?");
$stmt->execute(array($_GET['profile_id']));
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row){
echo"<li>".$row['year']." : ".$row['description']."</li>";
}
?>
</ul>
Done
</form>
</div>
</body>
</html>
ADD.PHP
<?php
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function validatePos() {
for($i=1; $i<=9; $i++) {
if ( ! isset($_POST['year'.$i]) ) continue;
if ( ! isset($_POST['desc'.$i]) ) continue;
$year = $_POST['year'.$i];
$desc = $_POST['desc'.$i];
if ( strlen($year) == 0 || strlen($desc) == 0 ) {
return "All fields are required";
}
if ( ! is_numeric($year) ) {
return "Position year must be numeric";
}
}
return true;
}
$failure=false;
$success=false;
if(isset($_POST['first_name'])&& isset($_POST['last_name'])
&& isset($_POST['email']) && isset($_POST['headline'])
&& isset($_POST['summary'])){
if(strlen($_POST['first_name'])<1 || strlen($_POST['last_name'])<1
||strlen($_POST['email'])<1 || strlen($_POST['headline'])<1
||strlen($_POST['summary'])<1){
$_SESSION['failure'] = "All values are required";
header("Location: add.php");
return;
}
if(!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
$_SESSION["failure"]="Email address must contain # sign.";
header("Location: add.php");
return;
}
$stmt = $pdo->prepare('INSERT INTO `profile`(`user_id`, first_name, last_name, email, headline, summary)
VALUES ( ?, ?, ?, ?, ?, ?)');
$stmt->execute(array($_SESSION['user_id'],
$_POST['first_name'],
$_POST['last_name'],
$_POST['email'],
$_POST['headline'],
$_POST['summary']));
$profile_id = $pdo->lastInsertId();
if($stmt==true){
$rank=1;
for($i=1; $i<=9; $i++) {
if ( ! isset($_POST['year'.$i]) ) continue;
if ( ! isset($_POST['desc'.$i]) ) continue;
$year = $_POST['year'.$i];
$desc = $_POST['desc'.$i];
$stmt = $pdo->prepare('INSERT INTO Position
(profile_id, `rank`, `year`, `description`)
VALUES ( ?, ?, ?, ?)');
$stmt->execute(array($profile_id, $rank, $year, $desc));
$rank++;
}
$_SESSION["success"]="Record Added";
header("Location: index.php");
return;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Rounak Simlai</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h1>Adding profile for<?php echo" ".$_SESSION['name']; ?></h1>
<form method="post">
<?php
if ( isset($_SESSION["failure"]) ) {
echo('<p style="color: red;">'.htmlentities($_SESSION["failure"])."</p>\n");
unset($_SESSION["failure"]);
}
?>
<p>First Name:
<input type="text" name="first_name" size="60"/></p>
<p>Last Name:
<input type="text" name="last_name" size="40"/></p>
<p>Email:
<input type="text" name="email"/></p>
<p>Headline:<br>
<input type="text" name="headline"/></p>
<p>Summary:<br/>
<textarea name="summary" rows="8" cols="80"></textarea></p>
<p>
Position: <input type="submit" id="addPos" value="+">
<div id="position_fields">
</div>
</p>
<input type="submit" value="Add">
Cancel
</form>
</div>
<script>
countPos = 0;
$(document).ready(function(){
window.console && console.log('Document ready called');
$('#addPos').click(function(event){
event.preventDefault();
if ( countPos >= 9 ) {
alert("Maximum of nine position entries exceeded");
return;
}
countPos++;
window.console && console.log("Adding position "+countPos);
$('#position_fields').append(
'<div id="position'+countPos+'"> \
<p>Year: <input type="text" name="year'+countPos+'" value="" /> \
<input type="button" value="-" \
onclick="$(\'#position'+countPos+'\').remove();return false;"></p> \
<textarea name="desc'+countPos+'" rows="8" cols="80"></textarea>\
</div>');
});
});
</script>
</body>
</html>
INDEX.PHP
<?php
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
<html>
<head>
<title>Rounak Simlai</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Rounak Simlai's Resume Registry</h1>
<?php
if (!isset($_COOKIE['data']))
{
echo '<p>Please log in</p>';
echo('<table border="1">'."\n");
$stmt= $pdo->prepare("SELECT profile_id, first_name, last_name, headline FROM `profile`");
$stmt->execute();
if($stmt->rowCount()==0){
echo "No Rows Found";
}
else{
echo"<thead><tr>
<th>Name</th>
<th>Headline</th>
</tr></thead>";
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td>";
echo''.htmlentities($row['first_name']).' '.htmlentities($row['last_name']).'';
echo("</td><td>");
echo(htmlentities($row['headline']));
echo("</td><td>");
}
}
}
if (isset($_COOKIE['data'])){
$msg=false;
if(isset($_SESSION["success"])) {
echo('<p style="color: green;">'.htmlentities($_SESSION["success"])."</p>\n");
unset($_SESSION['success']);
}
echo('<table border="1">'."\n");
$stmt= $pdo->prepare("SELECT profile_id, first_name, last_name, headline FROM `profile`");
$stmt->execute();
if($stmt->rowCount()==0){
$msg="No Rows Found";
}
else{
echo"<thead><tr>
<th>Name</th>
<th>Headline</th>
<th>Action</th>
</tr></thead>";
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td>";
echo''.htmlentities($row['first_name']).' '.htmlentities($row['last_name']).'';
echo("</td><td>");
echo(htmlentities($row['headline']));
echo("</td><td>");
echo('Edit / ');
echo('Delete');
echo("</td></tr>\n");
}
}
echo"<p>".htmlentities($msg)."</p>
<p>Add New Entry</p>
<p>Logout</p>
</div>";
}
?>
</body>
</html>
DELETE.PHP
<?php
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ( isset($_POST['delete']) && isset($_POST['profile_id']) ) {
$sql = "DELETE FROM `profile` WHERE profile_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($_POST['profile_id']));
$_SESSION['success'] = 'Record deleted';
header( 'Location: index.php' ) ;
return;
}
$stmt = $pdo->prepare("SELECT first_name, last_name, profile_id FROM `profile` where profile_id = ?");
$stmt->execute(array($_GET['profile_id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rounak Simlai</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Deleting profile</h1>
<form method="post">
<p>First Name: <?php echo($row['first_name']); ?> </p>
<p>Last Name: <?php echo($row['last_name']);?> </p>
<input type="hidden" name="profile_id" value="<?= $row['profile_id'] ?>">
<input type="submit" value="Delete" name="delete">
Cancel
</form>
</div>
</body>
</html>
LOGIN.PHP
<?php // Do not put any HTML above this line
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$salt = 'XyZzy12*_';
$failure = false; // If we have no POST data
// Check to see if we have some POST data, if we do process it
if ( isset($_POST['email']) && isset($_POST['pass']) ) {
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
if ( strlen($_POST['email']) < 1 || strlen($_POST['pass']) < 1 ) {
$_SESSION["failure"] = "Email and password are required";
header("Location: login.php");
return;
} else {
$check = hash('md5', $salt.$_POST['pass']);
$stmt = $pdo->prepare('SELECT `user_id`, `name` FROM users WHERE email = ? AND pass = ?');
$stmt->execute(array($_POST['email'], $check));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ( $row !== false ) {
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
setcookie('data','1999');
// Redirect the browser to index.php
header("Location: index.php");
return;
} else {
$_SESSION["failure"] = "Incorrect password";
error_log("Login fail ".$_POST['email']." $check");
header("Location: login.php");
return;
}
}
}
else{
$_SESSION["failure"] = "Email must have an # sign.";
header("Location: login.php");
return;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Rounak Simlai</title>
</head>
<body>
<?php require_once "bootstrap.php"; ?>
<div class="container">
<h1>Please Log In</h1>
<?php
if ( isset($_SESSION["failure"]) ) {
echo('<p style="color: red;">'.htmlentities($_SESSION["failure"])."</p>\n");
unset($_SESSION["failure"]);
}
?>
<form method="POST">
<label for="nam">User Name</label>
<input type="text" name="email" id="email"><br/>
<label for="id_1723">Password</label>
<input type="text" name="pass" id="id_1723"><br/>
<input type="submit" onclick="return doValidate();" value="Log In">
Cancel
</form>
<p><br>
For a password hint, view source and find a password hint
in the HTML comments.
<!-- Hint: The password is the three character name of the
programming language used in this class (all lower case)
followed by 123. -->
</p>
</div>
<script>
function doValidate() {
console.log('Validating...');
try {
addr = document.getElementById('email').value;
pw = document.getElementById('id_1723').value;
console.log("Validating addr="+addr+" pw="+pw);
if (addr == null || addr == "" || pw == null || pw == "") {
alert("Both fields must be filled out");
return false;
}
if ( addr.indexOf('#') == -1 ) {
alert("Invalid email address");
return false;
}
return true;
} catch(e) {
return false;
}
return false;
}</script>
</body>
</html>
LOGOUT.PHP
<?php
session_start();
setcookie('data');
unset($_SESSION['name']);
unset($_SESSION['user_id']);
header("Location: index.php");
?>

Admin page won't show

Warning: Cannot modify header information - headers already sent by
(output started at/admin/index.php:21) in
/var/www/web143366/html/admin/index.php on line 24
<?php
require_once('../config.php');
require_once('../php/functions.php');
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="admin.css">
<link rel="stylesheet" type="text/css" href="../layout.css">
</head>
<body>
<?php
if (!isset($_SESSION['adminid'])) {
header('Location: /admin/login');
} else {
?>
<div id="leftPanel">
<div class="przyciskPanelAdmina">Homepage</div>
<div class="przyciskPanelAdmina active">Dashboard</div>
<div class="przyciskPanelAdmina">Manage Accounts</div>
<div class="przyciskPanelAdmina">Add Account</div>
<div class="przyciskPanelAdmina">Add Category</div>
<div class="przyciskPanelAdmina">Messages</div>
<div class="przyciskPanelAdmina">Logout</div>
</div>
<div id="rightPanel">
<h3>Recent payments</h3>
<table>
<tr class='first'>
<td width='20%'>Account Login</td>
<td width='20%'>Account Password</td>
<td width='20%'>Date</td>
<td width='20%'>Amount</td>
<td width='20%'>Payment ID</td>
</tr>
<?php
$sql = $conn->prepare('SELECT accounts.login AS Login, accounts.password AS Pass, date, amount, paymentID FROM payments INNER JOIN accounts ON payments.accountId=accounts.id order by date DESC');
$sql->execute();
$result = $sql->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr><td width='20%'>" . $row['Login'] ."</td><td width='20%'>" . $row['Pass'] ."</td><td width='20%'>" . $row['date'] ."</td><td width='20%'>" . $row['amount'] ."$</td><td width='20%'>" . $row['paymentID'] ."</td></tr>";
}
?>
</table>
<div class="clear"></div>
</div>
<?php
}
?>
</body>
</html>
Edit all: This is the error. When I remove line 24 I get the following error.
Fatal error: Call to undefined method mysqli_stmt::get_result() in
/var/www/web143366/html/admin/login.php on line 32
Line 32: $result = $sql->get_result();
Code:
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Wrong email or password</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$p = $row['password'];
$uid = $row['id'];
}
if (password_verify($pass, $p)) {
$_SESSION['adminid'] = $uid;
header('Location: /admin');
} else {
echo "<h1>Wrong email or password 2</h1>";
}
}
}
Login.php=
<?php
require_once('../config.php');
require_once('../php/functions.php');
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
<body>
<?php
if (isset($_POST['loginBtn'])) {
$email = htmlspecialchars($_POST['mail']);
$pass = htmlspecialchars($_POST['password']);
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Wrong email or password</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$p = $row['password'];
$uid = $row['id'];
}
if (password_verify($pass, $p)) {
$_SESSION['adminid'] = $uid;
header('Location: /admin');
} else {
echo "<h1>Wrong email or password 2</h1>";
}
}
}
if (isset($_POST['forgotBtn'])) {
$code = randomChars(20);
$email = htmlspecialchars($_POST['mail']);
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>No user with that email</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$uid = $row['id'];
}
$sql = $conn->prepare('INSERT INTO resetpass (userID, code) VALUES (?, ?)');
$sql->bind_param('ss', $uid, $code);
$sql->execute();
$message = "Your reset link: " . "http://" .$_SERVER['SERVER_NAME'] . '/admin/login?r=' . $code;
$to = $email;
$title = "Reset Password";
if (sendEmail($to, $message, $title)) {
echo "Email with reset code has been sent";
} else {
echo "Error while sending email";
}
}
}
if (isset($_POST['resetBtn'])) {
$nPass = htmlspecialchars($_POST['nPass']);
$code = $_POST['code'];
$password = password_hash($nPass, PASSWORD_DEFAULT);
$sql = $conn->prepare('SELECT * FROM resetpass WHERE code = ?');
$sql->bind_param('s', $code);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Error</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$uid = $row['userID'];
}
$sql = $conn->prepare('UPDATE resetpass SET used = "1" WHERE code = ?');
$sql->bind_param('s', $code);
$sql->execute();
$sql = $conn->prepare('UPDATE admin SET password = ? WHERE id = ?');
$sql->bind_param('ss', $password, $uid);
$sql->execute();
echo "Password changed successfuly, you can now login";
}
}
?>
<?php
if (!isset($_SESSION['adminid'])) {
if (isset($_GET['forgot'])) { ?>
<form action="" method="POST">
<div class="formularzowyNaglowek">Account Email Address:</div>
<input type="email" name="mail" placeholder="Email address" required>
<input type="submit" name="forgotBtn" value="Reset">
</form>
<?php } else if (isset($_GET['r'])) { ?>
<form action="" method="POST">
<div class="formularzowyNaglowek">New Password:</div>
<input type="password" name="nPass" placeholder="New password" required>
<input type="hidden" name="code" value="<?php echo $_GET['r'] ?>" required>
<input type="submit" name="resetBtn" value="Reset">
</form>
<?php
} else { ?>
<h2 style="text-align: left;">Login to admin panel</h2>
<form action="" method="POST">
<div class="formularzowyNaglowek">Email Address:</div>
<input type="email" name="mail" placeholder="Email address" required>
<div class="formularzowyNaglowek">Password:</div>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" name="loginBtn" value="Login">
</form>
Forgot your password?
<?php
}
} else {
header('Location: /admin');
}
?>
</body>
</html>
The line header('Location: /admin/login'); will redirect to the login page when the user is not logged in.
The problem is, that the function header() doesnt work when there has been content outputted already (echo or html).
<?php
session_start(); // only if you havent called session_start in config.php or functions.php
require_once('../config.php');
require_once('../php/functions.php');
if (!isset($_SESSION['adminid'])) {
header('Location: /admin/login');
exit();
}
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="admin.css">
<link rel="stylesheet" type="text/css" href="../layout.css">
</head>
<body>
<div id="leftPanel">
<div class="przyciskPanelAdmina">Homepage</div>
<div class="przyciskPanelAdmina active">Dashboard</div>
<div class="przyciskPanelAdmina">Manage Accounts</div>
<div class="przyciskPanelAdmina">Add Account</div>
<div class="przyciskPanelAdmina">Add Category</div>
<div class="przyciskPanelAdmina">Messages</div>
<div class="przyciskPanelAdmina">Logout</div>
</div>
<div id="rightPanel">
<h3>Recent payments</h3>
<table>
<tr class='first'>
<td width='20%'>Account Login</td>
<td width='20%'>Account Password</td>
<td width='20%'>Date</td>
<td width='20%'>Amount</td>
<td width='20%'>Payment ID</td>
</tr>
<?php
$sql = $conn->prepare('SELECT accounts.login AS Login, accounts.password AS Pass, date, amount, paymentID FROM payments INNER JOIN accounts ON payments.accountId=accounts.id order by date DESC');
$sql->execute();
$result = $sql->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr><td width='20%'>" . $row['Login'] ."</td><td width='20%'>" . $row['Pass'] ."</td><td width='20%'>" . $row['date'] ."</td><td width='20%'>" . $row['amount'] ."$</td><td width='20%'>" . $row['paymentID'] ."</td></tr>";
}
?>
</table>
<div class="clear"></div>
</div>
</body>
</html>

Converting username, to userID for entry into a comments box

<?php
include("connection.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($conn,$_POST['username']);
$mypassword = mysqli_real_escape_string($conn,$_POST['password']);
$row['userID'] = $myuserid;
$sql = "SELECT * FROM u803621131_login.users WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_start("myuserid");
$_SESSION['login_user'] = $myusername;
$_SESSION['login_id'] = $myuserid;
header("location: welcome.php");
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login Page</title>
<style type = "text/css">
body {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
label {
font-weight:bold;
width:100px;
font-size:14px;
}
.box {
border:#666666 solid 1px;
}
</style>
</head>
<body bgcolor = "#FFFFFF">
<div align = "center">
<div style = "width:300px; border: solid 1px #333333; " align = "left">
<div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div>
<div style = "margin:30px">
<form action = "" method = "post">
<label>UserName :</label><input type = "text" name = "username" class = "box"/><br /><br />
<label>Password :</label><input type = "password" name = "password" class = "box" /><br/><br />
<input type = "submit" value = " Submit "/><br />
</form>
<div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div>
</div>
</div>
</div>
</body>
</html>
Login.php - The login page with all the changed parts, the actual login works as it should. although it is hard to tell if there are any other issues
<?php session_start();
include'../../connection.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" type="text/css" href=".../../../../style.css">
<title>Home</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<?php include('../../main/main.php');?>
</head>
<body>
<div class=containermain>
<h1>I5-6600k.php</h1>
<form action="ratepost.php" method="post">
<label for="rating">rating:</label>
<select name="rating" id="rating" value="rating" >
<option>
<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>
</option>
</select>
<input type="submit" value="Submit">
</form>
<h2>graphics card write up................</h2>
<?php echo "Hello " . $_SESSION['user']; ?>
<p> </p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
<div
class="fb-like"
data-share="true"
data-width="450"
data-show-faces="true">
</div>
<!---------------------------------------COMMENT BOX---------------------------------------------------->
<div class="comments" align="center">
<form action="" method="post" >
<textarea rows="4" cols="50" name="comment">
Please type a comment if you are logged in....
</textarea>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])) {
$id = $_SESSION['login_id'];
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '$comment', '1')";
if(mysqli_query($conn, $sqlinsert)){
header("Location: i5-6600k");
} else {
echo "ERROR: Could not able to execute $sqlinsert. " . mysqli_error($conn);
}
}
// close connection
$sql = "SELECT `users`.`username`, `comment`.`comment`, `comment`.`timestamp`\n"
. "FROM `users`\n"
. "LEFT JOIN `comment` ON `users`.`userID` = `comment`.`userID` \n"
. "where dCpuID = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Username</th><th>Comment</th><th>Timestamp</th>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["username"]. "</td><td>" . $row["comment"]."</td><td>" . $row["timestamp"]. "</td>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</div>
<?php include('../../assets/footer.php');?>
<div class="fb-comments" data-href="http://www.computercomparison.tk/#home" data-numposts="5"></div>
</body>
</html>
Have included entirety of 2nd page, incase there may be clashes with other parts of the code in the site that may be pointed out.
Also you will find lots of code in strange places, only testing bits at the mo.
<?php
include('connection.php');
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($conn,"select username, from users where username = '$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session = $row['username'];
if(!isset($_SESSION['login_user'])){
header("location:login.php");
}
?>
Have this session.php file, didn't think it was too relevant but changing it around did affect logging in and stuff, it is in good condition here, wonder if there is anything i need to change here too? it is linked to the welcome.php
Following the error message you connected a column for the comment authors ID to one in your account table using a foreign key.
As shown in your picture they're both INT. But you are trying to insert a VARCHAR (the username) into this column instead.
My approach would be to get the user's ID by a sql query or even better save the users ID to the session:
session_start();
$_SESSION['login_user'] = $usernameFromFormOrWhatever;
$_SESSION['login_id'] = $usersID;
So you can fill your userID column with it:
$id = $_SESSION['login_id'];
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '$comment', '1')";
Additionally the entered ID in your comments table must also appear in a row of your accounts table as ID of a user. Otherwise you will get an error message like you do now.

Having problems with sessions and pages in php

I really don't understand what I am doing here. I have this page profesor.php in which I want to insert some data into the database. After I submit the data from the form I want to be redirected to another page insert.php and display a message.
So I have profesor.php:
<?php
session_start();
if (isset($_SESSION['id'])) {
$fullname = $_SESSION['name'];
echo "<h1> Welcome " . $fullname . "</h1>";
} else {
$result = "You are not logged in yet";
}
if (isset($_POST['studname'])) {
include_once("dbConnect.php");
$studname = strip_tags($_POST['studname']);
$course = strip_tags($_POST['course']);
$grade = strip_tags($_POST['grade']);
$getStudidStm = "SELECT userid FROM users WHERE name = '$studname'";
$getStudidQuery = mysqli_query($dbCon, $getStudidStm);
$row = mysqli_fetch_row($getStudidQuery);
$studid = $row[0];
$_SESSION['studid'] = $studid;
$_SESSION['course'] = $course;
$_SESSION['grade'] = $grade;
header("Location: insert.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $fullname ;?></title>
</head>
<body>
<div id="wrapper">
<h2>Insert new grade</h2>
<form id="insertForm" action="insert.php" method="post" enctype="multipart/form-data">
Student: <input type="text" name="studname" /> <br />
Course : <input type="text" name="course" /> <br />
Grade : <input type="text" name="grade" /> <br />
<input type="submit" value="Insert" name="Submit" />
</form></div>
</form>
</body>
</html>
and insert.php
<?php
session_start();
if (isset($_SESSION['studid'])) {
include_once("dbConnect.php");
$studid = $_SESSION['studid'];
$course = $_SESSION['course'];
$grade = $_SESSION['grade'];
echo $studid;
echo $course;
echo $grade;
}
My problem is that insert.php doesn't display anything. I really don't understand what I'm doing wrong. Need some help.
your problem is in your form:
<form id="insertForm" action="insert.php" [...]
you send data to insert.php but all the 'magic' with
$_SESSION['studid'] = $studid;
$_SESSION['course'] = $course;
$_SESSION['grade'] = $grade;
you keep in profesor.php
Just change action="insert.php" to action="profesor.php" and it should work fine.

Inserting data into database not working

I am writing simple blog in PHP/MySQL and I have a problem to insert some data into my database. I am trying to add comment always receive an error - Comment not added. I can't figure it out what is wrong with the code. Is anybody able to help?
<?php
if(!isset($_GET['id'])) {
header('Location: index.php');
exit();
} else {
$id = $_GET['id'];
}
if(!is_numeric($id)) {
header('Location: index.php');
}
// Include database connection
include('includes/db_connect.php');
$sql = "SELECT post_title, post_body FROM posts WHERE post_id='$id'";
$query = $db->query($sql);
//echo $query->num_rows;
if($query->num_rows != 1) {
header('Location: index.php');
exit();
}
if(isset($_POST['submit-comment'])) {
$email = $_POST['email'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$email = $db->real_escape_string($email);
$name = $db->real_escape_string($name);
$comment = $db->real_escape_string($comment);
$id = $db->real_escape_string($id);
if($email && $name && $comment) {
$sqlComment = "INSERT INTO comments (post_id, email, name, comment) VALUES ('$id','$email','$name','$comment')";
$queryComment = $db->query($sqlComment);
if($queryComment) {
echo "Comment was added";
} else {
echo "Comment not added";
}
} else {
echo "Error";
}
}
?>
<! DOCTYPE html >
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--><html class=""><!--<![endif]-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog System</title>
<link rel="stylesheet" href="css/application.css" type="text/css">
<style type="text/css">
label {
display: block;
}
</style>
</head>
<body>
<div id="container">
<div id="post">
<?php
$row = $query->fetch_object();
echo "<h2>" . $row->post_title . "</h2>";
echo "<p>" . $row->post_body . "</p>";
?>
</div>
<hr>
<div id="add-comments">
<form action="<?php echo $_SERVER['PHP_SELF'] . '?id=' . $id ?>" method="post">
<label for="email">Email Address:</label>
<input type="text" name="email" id="email"><br>
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="comment">Comment</label>
<textarea name="comment" id="comment" cols="30" rows="10"></textarea><br>
<br><br>
<input type="submit" name="submit-comment" value="Post your comment" id="postyourcomment">
</form>
</div>
</div>
<script type="text/javascript" src="js/application.min.js"></script>
</body>
</html>
<?php
if(isset($_POST['submit-comment'])) {
if(!isset($_GET['id'])) {
header('Location: index.php');
exit();
} else {
$id = $_GET['id'];
}
if(!is_numeric($id)) {
header('Location: index.php');
}
// Include database connection
include('db_connect.php');
$sql = "SELECT post_title, post_body FROM posts WHERE post_id=".$id." ";
$query = $db->query($sql);
//echo $query->num_rows;
if($query->num_rows != 1) {
header('Location: index.php');
exit();
}
$email = $_POST['email'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$email = $db->real_escape_string($email);
$name = $db->real_escape_string($name);
$comment = $db->real_escape_string($comment);
$id = $db->real_escape_string($id);
if($email && $name && $comment) {
$sqlComment = "INSERT INTO comments (post_id, email, name, comment) VALUES (".$id.",'".$email."','".$name."','".$comment."')";
$queryComment = $db->query($sqlComment);
if($queryComment) {
echo "Comment was added";
} else {
echo "Comment not added";
}
} else {
echo "Error";
}
}
?>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog System</title>
<link rel="stylesheet" href="file:///C|/Users/Jaydeep Jivani/Desktop/css/application.css" type="text/css">
<style type="text/css">
label {
display: block;
}
</style>
</head>
<body>
<div id="container">
<div id="post">
<?php
$row = $query->fetch_object();
echo "<h2>" . $row->post_title . "</h2>";
echo "<p>" . $row->post_body . "</p>";
?>
</div>
<hr>
<div id="add-comments">
<form action=<?=$_SERVER['PHP_SELF']?> method="get">
<input type="hidden" name="id" value=<?=$id?> />
<label for="email">Email Address:</label>
<input type="text" name="email" id="email"><br>
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="comment">Comment</label>
<textarea name="comment" id="comment" cols="30" rows="10"></textarea><br>
<br><br>
<input type="submit" name="submit-comment" value="Post your comment" id="postyourcomment">
</form>
</div>
</div>
<script type="text/javascript" src="file:///C|/Users/Jaydeep Jivani/Desktop/js/application.min.js"></script>
</body>
</html>
Thank you everyone for help. I found a problem which was related to my database, unfortunately I constructed table with comment_id and forgot to add AI attribute.
Thanks to #tadman I was able to rewrite my code and here is the final working result:
if(isset($_POST['submit-comment'])) {
$email = $_POST['email'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$email = $db->real_escape_string($email);
$name = $db->real_escape_string($name);
$comment = $db->real_escape_string($comment);
$id = $db->real_escape_string($id);
if($email && $name && $comment) {
// Prepare statemnt
$sqlComment = "INSERT INTO comments (post_id, email, name, comment) VALUES (?, ?, ?, ?)";
$queryComment = $db->prepare($sqlComment);
$queryComment->bind_param('ssss', $id, $email, $name, $comment);
// Execute prepared statement
$queryComment->execute();
if($queryComment) {
echo "Comment was added.";
} else {
echo "There was a problem. Error: " . mysqli_error($db);
}
// Close statement
$queryComment->close();
} else {
echo "Error";
}

Categories