Inserting data into database not working - php

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";
}

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>

Information don't post in database

I try to implement an sign in form based on webcam image, apparently, i don't errors in code, but information don't posted in database.
Here is my index with php code for insert information in database:
<?php
if (isset($_POST['desc'])) {
if (!isset($_POST['iscorrect']) || $_POST['iscorrect'] == "") {
echo "Sorry, important data to submit your question is missing. Please press back in your browser and try again and make sure you select a correct answer for the question.";
exit();
}
if (!isset($_POST['type']) || $_POST['type'] == "") {
echo "Sorry, there was an error parsing the form. Please press back in your browser and try again";
exit();
}
require_once("scripts/connect_db.php");
$name = $_POST['name'];
$email = $_POST['email'];
$name = mysqli_real_escape_string($connection, $name);
$name = strip_tags($name);
$email = mysqli_real_escape_string($connection, $email);
$email = strip_tags($email);
if (isset($_FILES['image'])) {
$name = $_FILES['image']['tmp_name'];
$image = base64_encode(
file_get_contents(
$_FILES['image']['tmp_name']
)
);
}
$sql = mysqli_query($connection, "INSERT INTO users (name,email,image) VALUES ('$name', '$email','$image')")or die(mysqli_error($connection));
header('location: index.php?msg=' . $msg . '');
$msg = 'merge';
}
?>
<?php
$msg = "";
if (isset($_GET['msg'])) {
$msg = $_GET['msg'];
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Licenta Ionut</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!-- font files -->
<link href='//fonts.googleapis.com/css?family=Muli:400,300' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Nunito:400,300,700' rel='stylesheet' type='text/css'>
<!-- /font files -->
<!-- css files -->
<link href="css/style.css" rel='stylesheet' type='text/css' media="all" />
<link href="web.js" rel='stylesheet' type='text/css' media="all" />
<script type="text/javascript" src="web.js"></script>
<!-- /css files -->
</head>
<body>
<p style="color:#06F;"><?php echo $msg; ?></p>
<h1>LogIn with Webcam Password</h1>
<div class="log">
<div class="content1">
<h2>Sign In Form</h2>
<form>
<input type="text" name="userid" value="USERNAME" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = 'USERNAME';
}">
<input type="password" name="psw" value="PASSWORD" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = 'PASSWORD';}">
<div class="button-row">
<input type="submit" class="sign-in" value="Sign In">
<input type="reset" class="reset" value="Reset">
<div class="clear"></div>
</div>
</form>
</div>
<div class="content2">
<h2>Register</h2>
<form action="index.php", name="index.php" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" value="Nume">
<input type="text" id="email" name="email" value="EmailAdress">
<br>
<script type="text/javascript" src="webcam.js"></script>
<script language="JavaScript">
document.write(webcam.get_html(320, 240));
</script>
<div class="button-row">
<input class="sign-in" type=button value="Configure" onClick="webcam.configure()" class="shiva">
<input class="reset" type="submit" value="Register" id="image" onClick="take_snapshot()" class="shiva">
</div>
</form>
</div>
<div class="clear"></div>
</div>
</body>
</html>
And here is the script for connection to database:
<?php
$db_host = "localhost";
// Place the username for the MySQL database here
$db_username = "Ionut";
// Place the password for the MySQL database here
$db_pass = "1993";
// Place the name for the MySQL database here
$db_name = "users";
// Run the connection here
$connection=mysqli_connect("$db_host","$db_username","$db_pass") or die (mysqli_connect_error());
mysqli_select_db($connection,"$db_name") or die ("no database");
?>
I don't find error in code and i need your advice/help!
Thank you for interest about my problem!
To solve a problem like this, break the problem into parts.
(1) First, what is the PHP file receiving? At the top of the PHP file, insert:
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
die('-----------------------------------');
(2) If that doesn't reveal the problem, next step is to duplicate the PHP file and in the second copy, HARD CODE the information you will be submitting at the top (replacing the PHP data that would normally be submitted):
<?php
$_POST['desc'] = 'TEST - Description';
$_POST['iscorrect'] = 'what it should be';
$_POST['type'] = 'TEST - Type';
etc
Then, run that modified file and see if the data is submitted.
(3) If that doesn't reveal the problem, keep working with the duplicate PHP file and add echo statements at various places to see where the file is breaking. For example:
$name = $_POST['name'];
$email = $_POST['email'];
$name = mysqli_real_escape_string($connection, $name);
echo 'HERE 01';
$name = strip_tags($name);
$email = mysqli_real_escape_string($connection, $email);
$email = strip_tags($email);
echo 'HERE 02';
if (isset($_FILES['image'])) {
$name = $_FILES['image']['tmp_name'];
$image = base64_encode(
file_get_contents(
$_FILES['image']['tmp_name']
)
);
}
echo 'HERE 03';
$sql = mysqli_query($connection, "INSERT INTO users (name,email,image) VALUES ('$name', '$email','$image')")or die(mysqli_error($connection));
echo 'HERE 04: $sql = ' .$sql;

registration page with php and mysql not working

Trying to create a registration page that adds new users to a database with php, i can't seem to get the information to add to the database, it is most likely something stupid that I have doing wrong or have missed out in my code.
Here is my code
<?php
session_start();
?>
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="author" content="" />
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="boilerplate/js/vendor/modernizr-2.7.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="../css/party.css" media="screen" />
<script type="text/javascript" src="javascript/jquery_min.js"></script>
<script type="text/javascript" src="javascript/cookies.js"></script>
</head>
<body>
<?php include 'header.php'; ?>
<div id="container_register">
<div id="content_register">
<h2>Register</h2>
<?php
include "connect.php";
if (isset($_POST['formsubmitted'])) {
$error = array(); //Declare An Array to store any error message
if (empty($_POST['up_username'])) { //if no name has been supplied
$error[] = 'Please Enter a name '; //add to array "error"
} else {
$name = $_POST['up_username']; //else assign it a variable
}
if (empty($_POST['up_email'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",
$_POST['up_email'])) {
//regular expression for email validation
$Email = $_POST['up_email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['up_password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['up_password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM users WHERE Email ='$Email'";
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) { //if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$query_insert_user =
"INSERT INTO `users` ( `Username`, `Email`, `Password`) VALUES ( '$name', '$Email', '$Password')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
echo '<div class="success">Thank you for
registering! </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a systemdiv>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email address has already been registered.</div>';
}
} else { //If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc); //Close the DB Connection
// End of the main Submit conditional.
?>
<form name="signup" id="signup" action="register.php" method="post">
<label for="up_username"><span class="required">*</span> Name</label>
<input type="text" name="up_username" id="up_username" placeholder="First Surname" />
<br>
<label for="up_email"><span class="required">*</span> Email</label>
<input type="email" name="up_email" id="up_email" placeholder="username#email.com" />
<br>
<label for="up_password"><span class="required">*</span> Password</label>
<input type="password" name="up_password" id="up_password" />
<br>
<label for="up_password_c"><span class="required">*</span> Confirm Password</label>
<input type="password" name="up_password_c" id="up_password_c" />
<div class="div_submit">
<input id="register_submit" type="submit" value="Sign up" />
</div>
</form><!--#sign up end-->
<p class="required">* Indicates a required field</p>
</div><!--content div end-->
</div><!--container div end-->
The If conditions you have written is always retrun false.
To Resolve this Please set the name attribute of submit button to formsubmitted like as follows
<input id="register_submit" name= "formsubmitted" type="submit" value="Sign up" />
Since the formsubmitted is not present inside the form the values is not set for $_POST['formsubmitted'], So the If part of your if statement is never executed.
Here is a similar script I often use, feel free to alter it at your discretion.
<?
if ($_POST['submit']){
$username = $_POST['username'];
$password = md5($_POST['password']);
$confirm = $_POST['confirm'];
$email = $_POST['email'];
if (!$username || !$password || !$confirm || !$email){
$response = "Please fill in all the boxes";
}else{
$check = mysql_num_rows(mysql_query("SELECT * FROM users WHERE username='$username'"));
if ($check != 0){
$response = "Username taken, Please choose an alternative";
}else{
$check = mysql_num_rows(mysql_query("SELECT * FROM users WHERE email='$email'"));
if ($check != 0){
$response = "This Email has already been registered";
}else{
mysql_query("INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES ('', '$username', '$password', '$email');");
$response = "Account Created";
}
}
}
}
echo "$response"; ?>

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

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()";

Categories