First page:
<?php
session_start();
//db info
$conn = new mysqli("$server","$user_name","$password","$database");
$sql = "SELECT id FROM Client_Information order by id desc limit 1";
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row = $result->fetch_assoc()) {
$id=$row['id'] + 1;
}
}
$_SESSION['id'] = $id;
$sitename = $_POST['sitename'];
$sitetype = $_POST['sitetype'];
$color1 = $_POST['color1'];
$color2 = $_POST['color2'];
$color3 = $_POST['color3'];
$color4 = $_POST['color4'];
$sitedescription = $_POST['sitedescription'];
$aboutme = $_POST['aboutme'];
$contactname = $_POST['contactname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$address = $_POST['address'];
if (isset($sitename) && isset($sitetype) && isset($color1)
&& isset($color2) && isset($contactname) && isset($phone)
&& isset($email) && isset($address) && isset($sitedescription)
&& isset($aboutme)) {
$sql = "INSERT INTO Client_Information (id, sitename, sitetype, color1, color2,
color3, color4, sitedescription, aboutme,
contactname, phone, email, address, timestamp)
VALUES ('$id', '$sitename', '$sitetype', '$color1', '$color2',
'$color3', '$color4', '$sitedescription', '$aboutme',
'$contactname', '$phone', '$email', '$address',
CURRENT_TIMESTAMP)";
$conn->query($sql);
header('Location: images.php');
}
mysqli_close($conn);
?>
Second page:
<?php
session_start();
echo $_SESSION['id'];
//db info
$conn = new mysqli("$server","$user_name","$password","$database");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$wherevar = $_SESSION['id'];
$exsitename1 = $_POST['exsitename1'];
$exsitename2 = $_POST['exsitename2'];
$exsitename3 = $_POST['exsitename3'];
$exsitename4 = $_POST['exsitename4'];
$exsiteurl1 = $_POST['exsiteurl1'];
$exsiteurl2 = $_POST['exsiteurl2'];
$exsiteurl3 = $_POST['exsiteurl3'];
$exsiteurl4 = $_POST['exsiteurl4'];
$exsitedescr1 = $_POST['exsitedescr1'];
$exsitedescr2 = $_POST['exsitedescr2'];
$exsitedescr3 = $_POST['exsitedescr3'];
$exsitedescr4 = $_POST['exsitedescr4'];
if (isset($exsitename1) && isset($exsitename2) && isset($exsitename3) && isset($exsitename4)
&& isset($exsiteurl1) && isset($exsiteurl2) && isset($exsiteurl3) && isset($exsiteurl4)
&& isset($exsitedescr1) && isset($exsitedescr2) && isset($exsitedescr3) && isset($exsitedescr4)) {
$sql = "UPDATE Client_Information
SET exsitename1='$exsitename1', exsitename2='$exsitename2', exsitename3='$exsitename3',
exsitename4='$exsitename4', exsiteurl1='$exsiteurl1', exsiteurl2='$exsiteurl2',
exsiteurl3='$exsiteurl3', exsiteurl4='$exsiteurl4', exsitedescr1='$exsitedescr1',
exsitedescr2='$exsitedescr2', exsitedescr3='$exsitedescr3', exsitedescr4='$exsitedescr4'
WHERE id = '$wherevar'";
$conn->query($sql);
header('Location: index.php');
}
session_destroy();
mysqli_close($conn);
?>
So the first page works fine and inserts all the data into the db, but when the second page is ran, it doesn't update the same row that was inserted on the first page. It just leaves all those variable.
On the second page, I'm trying to have it edit the row that was just created.
Related
I had created a database which named student with ID, name, mat_number, specialty, age, and gender, in a PHP application.
I do not want the name or mat_number be taken in more than once.
I have done the connection to my database in a different page and called it in the add student page.
This following codes is for a faculty database collection
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender))
{
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}
else{
echo "Error: Complete all records";
}
}
?>
I want to get an error message demanding for a change if the 2 fields already exist in the database.
first name to check in database if already exist the record.
if no record run sql insert command.
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
$sql = "SELECT * FROM `student` WHERE name = "'.$name.'" and UB_number = '".$matNo."'";
$conn->query($sql);
$cnt = $conn->rowCount();
if($cnt == 0){
$sql = "INSERT INTO `student`
(`name`, `UB_number`, `age`,`sex`, `specialty`)
VALUES
('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}else{
echo "Error: Complete all records";
}
}
If you would like to insert a new record to DB only if one doesn't exist which has the same name or mat_number then you first need to execute SELECT statement to see if it exists.
Using MySQLi:
<?php
include 'mysqli.php';
$conn = $mysqli;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->bind_param('ss', $name, $matNo);
$stmt->execute();
$stmt->bind_result($exists);
$stmt->fetch();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)');
$stmt->bind_param('sssss', $name, $matNo, $age, $gender, $specialty);
$stmt->execute();
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
Using PDO:
<?php
include 'lib.php';
$conn = $pdo;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->execute([$name, $matNo]);
$exists = $stmt->fetchColumn();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)')
->execute([$name, $matNo, $age, $gender, $specialty]);
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
hope this may be helpfull to you. In here I asume that you are not using any framework. But if you use a framework there are plenty of easy methods to do this.In here I have checked only name field. You should update code as you wants. Also it it better if you could validate your inputs before check. Like trim(). Thanks
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
//after user click the submit button
$sql_Select_Stundets = "SELECT * FROM student WHERE name = '$name' ";
// query the sql with db connection
$result_sql_Select_Stundets = mysqli_query($conn,$sql_Select_Stundets);
//Now check the row count to verify the output if there is any match
$rowcount=mysqli_num_rows($result);
//Now write insert inside if condition
if( $rowcount >0 ) {
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender)) {
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
bheader("Location: index.php");
}else{
echo "Error: Complete all records";
}
}else{
echo "<script>
alert('sorry this name is already available');
</script>";
}
}
?>
Can someone find the problem?
It doesn't give any errors, but new rows don't appear in the database and I don't know the problem is.
if (isset( $_REQUEST['signupnbtn'] ) ) {
$age = mysqli_real_escape_string($con,$_REQUEST['ageinput']);
$discord = mysqli_real_escape_string($con,$_REQUEST['discordinput']);
$email = mysqli_real_escape_string($con,$_REQUEST['emailinput']);
$tmp = mysqli_real_escape_string($con,$_REQUEST['tmpinput']);
$steam = mysqli_real_escape_string($con,$_REQUEST['steaminput']);
$datum = date("d-m-Y");
$errorcode = 0;
$q = "INSERT INTO `admissions` (age, discord, email, tmp, steam, datum)
VALUES ('$age', '$discord', '$email', '$tmp', '$steam', '$datum')";
$query2 = "SELECT email FROM `admissions` WHERE email='$email'";
$sql = mysqli_query($con,$query2);
$countrows = mysqli_num_rows($sql);
if($countrows >= 1){
$errorcode = 1;
}else {
$result = mysqli_query($con,$q);
}
if ($result) {
$errorcode = 4;
}
}
$q = "INSERT INTO admissions (age, discord, email, tmp, steam, datum) VALUES ('$age', '$discord', '$email', '$tmp', '$steam', '$datum')";
Problem solved, the date should be in "Y-m-d" format instead of "d-m-Y" as below:
if (isset( $_REQUEST['signupnbtn'] ) ) {
$age = mysqli_real_escape_string($con,$_REQUEST['ageinput']);
$discord = mysqli_real_escape_string($con,$_REQUEST['discordinput']);
$email = mysqli_real_escape_string($con,$_REQUEST['emailinput']);
$tmp = mysqli_real_escape_string($con,$_REQUEST['tmpinput']);
$steam = mysqli_real_escape_string($con,$_REQUEST['steaminput']);
$datum = date("Y-m-d");
$errorcode = 0;
$q = "INSERT INTO `admissions` (age, discord, email, tmp, steam, datum)
VALUES ('$age', '$discord', '$email', '$tmp', '$steam', '$datum')";
$query2 = "SELECT email FROM `admissions` WHERE email='$email'";
$sql = mysqli_query($con,$query2);
$countrows = mysqli_num_rows($sql);
if($countrows >= 1){
$errorcode = 1;
}else {
$result = mysqli_query($con,$q);
}
if ($result) {
$errorcode = 4;
}
}
I have the error mentioned in the title. It occurs when I click the submit button on the form. Here is my form handle file (I don't think that its necessary to copy the form codes):
<?php
$servername = "localhost";
$username = "sabashel_sabaadm";
$password = "saba1365%karaj#*";
$dbname = "sabashel_saba";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$fname = $lname = $gender = $birthdate = $organization = $degree = $field = $address = $post_code = $mobile = $email = $check_1 = $check_2 = $check_3 = $check_4 = $check_5 = $check_6 = $check_7 = $check_8 "";
$check_9 = $check_10 = $check_11 = $check_12 = $check_13 = $description = $person_image = "";
if(isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['gender']) && isset($_POST['birthdate']) && isset($_POST['degree']) && isset($_POST['filed-of-study']) && isset($_POST['address']) && isset($_POST['post-code']) && isset($_POST['mobile']) && isset($_POST['email']) && isset($_POST['check-1']) && isset($_POST['check-2']) && isset($_POST['check-3']) && isset($_POST['check-4']) && isset($_POST['check-5']) && isset($_POST['check-6']) && isset($_POST['check-7']) && isset($_POST['check-8']) && isset($_POST['check-9']) && isset($_POST['check-10']) && isset($_POST['check-11']) && isset($_POST['check-12']) && isset($_POST['check-13']) && isset($_POST['description']) && isset($_POST['person-iamge'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$gender = $_POST['gender'];
$birthdate = $_POST['birdthdate'];
$organization = $_POST['organization'];
$degree = $_POST['degree'];
$field = $_POST['field-of-study'];
$address = $_POST['address'];
$post_code = $_POST['post-code'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$check_1 = $_POST['check-1'];
$check_2 = $_POST['check-2'];
$check_3 = $_POST['check-3'];
$check_4 = $_POST['check-4'];
$check_5 = $_POST['check-5'];
$check_6 = $_POST['check-6'];
$check_7 = $_POST['check-7'];
$check_8 = $_POST['check-8'];
$check_9 = $_POST['check-9'];
$check_10 = $_POST['check-10'];
$check_11 = $_POST['check-11'];
$check_12 = $_POST['check-12'];
$check_13 = $_POST['check-13'];
$description = $_POST['description'];
$person_image = $_POST['person-image'];
$iftest = true;
}
if ($iftest == true) {
$query = "INSERT INTO volunteer (fname, lname, gender, organization, degree, field, address, post_code, mobile, email, check_1, check_2, check_3, check_4, check_5, check_6, check_7, check_8, check_9, check_10, check_11, check_12, check_13, description, person_image, birthdate) VALUES ('$fname', '$lname', '$gender', '$organization', '$degree', '$field', '$address', '$post_code', '$mobile', '$email', '$check_1', '$check_2', '$check_3', '$check_4', '$check_5', '$check_6', '$check_7', '$check_8', '$check_9', '$check_10', '$check_11', '$check_12', '$check_13', '$description', '$person_image', '$birthdate')";
}
$result = mysqli_query($conn, $query);
if ($result) {
header('Location: http://sabashelter.com/success');
}
else {
header('Location: http://sabashelter.com/fail');
}
}
$conn->close();
?>
And to mention: I have the same exact problem with another page which does the same thing and tries to add a lot of values into the database using the same code. I'm wondering if the problem in this page solves, the same method can be done to the other page as well.
As #CBroe rightly says, check your log files first. It would appear that you are missing an = on line 14.
$fname = $lname = $gender = $birthdate = $organization = $degree = $field = $address = $post_code = $mobile = $email = $check_1 = $check_2 = $check_3 = $check_4 = $check_5 = $check_6 = $check_7 = $check_8 = "";
Furthermore, you have a stray } on line 60.
Your error log file will help you resolve these issues.
I want to add one to the last inserted value of a column in a the database. I am not getting any error but the query is not adding 1 to the last inserted value.
Note; I used MAX(id) to get the max id but it's not adding 1 to it. What am I doing wrong?
<?php
session_start();
ob_start();
if (isset($_POST['submit'])) {
$pin = htmlspecialchars(trim($_POST['pin']));
$surName = htmlspecialchars(trim($_POST['surName']));
$firstName = htmlspecialchars(trim($_POST['firstName']));
$otherName = htmlspecialchars(trim($_POST['otherName']));
$email = htmlspecialchars(trim($_POST['email']));
$passWord = md5(trim($_POST['passWord']));
$confirmPass = md5(trim($_POST['confirmPass']));
$date_added = date('Y.m.d - H:i:s');
$year = (100 . 'L');
$studentId = 201600001;
if ((empty($pin && $surName && $firstName && $otherName && $email && $passWord && $confirmPass) == false) && ($passWord) == ($confirmPass))
{
include "dbconnect.php";
$sql = "SELECT * FROM `sono` WHERE `pin`='$pin'";
$check = mysqli_query($dbconnect, $sql);
$numrow = mysqli_num_rows ($check);
if ($numrow == 1)
{
$rows=mysqli_fetch_assoc($check);
$Email = $rows['eMail'];
if ($Email == false)
{
$query = "SELECT * FROM `sono` WHERE `eMail`='$email'";
$check = mysqli_query($dbconnect, $query);
$numrow = mysqli_num_rows($check);
if ($numrow == 0)
{
$sql = "INSERT INTO `sono_nextofkin` (`eMail`) VALUES ('$email')";
mysqli_query($dbconnect, $sql);
$query = "INSERT INTO `sono_0level_results` (`eMail`) VALUES ('$email')";
mysqli_query($dbconnect, $query);
$query = "UPDATE `sono` SET `surName`='$surName', `firstName`='$firstName', `otherName`='$otherName', `eMail`='$email', `passWord`='$passWord', `confirmPass`='$confirmPass', `date_added`='$date_added', `year`='$year', `studentid`='$studentId' WHERE `pin`='$pin'";
mysqli_query($dbconnect, $query);
$max = "SELECT * MAX(`studentid`) FROM `sono`";
$max2 = mysqli_query ($dbconnect, $max);
$update = "UPDATE `sono` SET `MAX(`studentid`) = '$studentId' + 1 WHERE `pin`='$pin'";
mysqli_query ($dbconnect, $update);
$query = "SELECT `id` as idmax FROM `sono`";
$result = mysqli_query($dbconnect, $query) or die (mysqli_error($dbconnect));
$rowa = mysqli_fetch_array($result);
$rw = $rowa['idmax'];
$rwo = $rw+1;
$rwo = str_pad($rwo,4,'0',STR_PAD_LEFT);
$sql = "UPDATE `sono` SET `id`='$rwo' WHERE `pin`='$pin'";
$result = mysqli_query($dbconnect, $sql);
$_SESSION['surName'] = $surName;
$_SESSION['firstName'] = $firstName;
$_SESSION['otherName'] = $otherName;
$_SESSION['email'] = $email;
$_SESSION['passWord'] = $passWord;
$msg= "<p style = 'color: green; padding-left: 0'>Registration successful,<a href='passport.php'> >>>Click here to proceed<<<</a></p>";
} else
$msg= "<p style = 'color: red; padding-left: 0'>Email already used, use another valid email to register</p>";
} else
$msg= "<p style = 'color: red; padding-left: 0'>The pin has been used</p>";
} else
$msg= "<p style = 'color: red; padding-left: 0'>The pin enter does not exist</p>";
} else
$msg= "<p style = 'color: red; padding-left: 0'>Please enter your names, pin, email and password to start registration</p>";
}
?>
you should do like
$update = "UPDATE `sono` SET `studentid` = MAX(`studentid`) + 1 WHERE `pin`='$pin'";
OR
Use LAST_INSERT_ID() from your SQL query.
OR
You can also use mysqli_insert_id() to get it using PHP.
I have a registration form that the user enters data in. Then after it is posted to the same page and checked for null fields, the variables are put in the $_SESSION array and the user is directed to another form to enter another set of data in a table. After posting those variables, the variables from the previous page are extracted from $_SESSION and the new values are checked for null entries. After they are checked in a for loop, php script mysteriously stops (die("<h1> GOT HERE! </h1>") no longer appears on the screen) and the page keeps loading. After waiting for a while the page reloads itself.
I've been using die() for a while now to find the error, but it just doesn't echo between the for-loop and the if statement, and there is no apparent reason why it shouldn't. Here have a look:
<?php
session_start();
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($_SESSION["registering"] != 1){
die("This page is to be used only when registering. Go to home page and select the seminar you want and click Register");
}else if($_SESSION["registered"] == 1){
die("You have already registered. Thank you. You can no longer access this page. To view your registration report, click here. ");
}else{
$id = sanitize($_SESSION["id"]);
$attendees = sanitize($_SESSION["attendees"]);
$ref_code = sanitize($_SESSION["Ref_Code"]);
$email = sanitize($_SESSION["email"]);
$prefix = sanitize($_SESSION["prefix"]);
$first_name = sanitize($_SESSION["first_name"]);
$last_name = sanitize($_SESSION["last_name"]);
$company = sanitize($_SESSION["company"]);
$address1 = sanitize($_SESSION["address1"]);
$address2 = sanitize($_SESSION["address2"]);
$user_city = sanitize($_SESSION["city"]);
$phone = sanitize($_SESSION["phone"]);
$responsibility = sanitize($_SESSION["responsibility"]);
$who_referred = sanitize($_SESSION["who-referred"]);
$role = sanitize($_SESSION["role"]);
$server = "MYREAL_DATABASE_SERVER";
$username = "CORRECT_USERNAME";
$password = "CORRECT_PASSWORD";
$dbname = "DB_NAME";
$conn = new mysqli($server, $username, $password, $dbname);
$query = "
SELECT *
FROM Seminar_Detail
WHERE Detail_id = '". $id ."'
";
$result = $conn->query($query);
if($result->num_rows == 0 ){
header("Location: ManagementSeminars.php");
}
$seminar = $result->fetch_assoc();
$name = $seminar["Seminar_Name"];
$city = $seminar["City"];
$from = $seminar["From"];
$to = $seminar["To"];
$fee = '';
$query = "SELECT Value FROM Fee WHERE Seminar_Name = '". $name ."' AND Currency = 'GBP'";
$result = $conn->query($query);
if($result->num_rows > 0){
$row = $result->fetch_assoc();
$fee = $row["Value"];
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$terminate = 0;
for($i = 1; i < ($attendees + 1); $i++){
if(isset($_POST["prefix-".$i]) && isset($_POST["first_name-".$i]) && isset($_POST["last_name-".$i]) && isset($_POST["position-".$i])){
$terminate = 0;
}else{
$terminate = 1;
}
}
die("<h1>".$terminate."</h1>");
if($terminate != 1){
$server = "SERVER";
$username = "USERNAME";
$password = "PASSWORD";
$dbname = "DBNAME";
$conn = new mysqli($server, $username, $password, $dbname);
$query = "
INSERT INTO Registry (Seminar_Name, Number_Attendees, Email, Prefix, First_Name, Last_Name, Company, `Address 1`, `Address 2`, City, Phone, Responsibility, Role, Who_Referred, Ref_Code)
VALUES ('". $name ."', '". $attendees ."', '".$email."', '".$prefix."', '".$first_name."', '".$last_name."', '".$company."', '".$address1."', '".$address2."', '".$user_city."', '".$phone."', '".$responsibility."', '".$role."', '".$who_referred."', '".$ref_code."')
";
$conn->query($query);
//ignore this part please
/*$query = "SELECT Registry_ID FROM Registry WHERE Ref_Code = '". $_SESSION["Ref_Code"] ."'";
$result = $conn->query($query);
$row = $result->fetch_assoc();
$registry_id = $row["Registry_ID"];
$attendee_first_name = "";
$attendee_last_name = "";
$attendee_position = "";
$stmt = $conn->prepare("
INSERT INTO Attendee (First_Name, Last_Name, Position, Registry_ID)
Values (?, ?, ?, ?)
");
$stmt->bindParam("ssss", $attendee_first_name, $attendee_last_name, $attendee_position, $registry_id);
for($i = 1; $i < $_SESSION["attendees"] + 1; $i++){
$attendee_first_name = sanitize($_POST["first_name-".$i]);
$attendee_last_name = sanitize($_POST["last_name-".$i]);
$attendee_position = sanitize($_POST["position-".$i]);
$stmt->execute();
}*/
}else{
$errorMessage = "<div class='alert alert-danger alert-dismissable'>
<strong>Oops!</strong> You have not entered all values.
</div>";
}
}
}
?>
I am positive that it is not a syntax error. Any help is appreciated!
The problem might be in this line
for($i = 1; i < ($attendees + 1); $i++){
You missed $ sign in i. It should be:
for($i = 1; $i < ($attendees + 1); $i++){
Having used error reporting, would have signaled an undefined constant i notice.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.