Can't insert and update at the same time - php

I have the code below and i can't figure why it's not working. The problem it's that i can insert a post with it, but when i try to update a post it's create a new page instead to update.
I have tried to remove isset from if(isset($_POST['id']) != 'null') and the update work, but then the insert doesn't work anymore.
Any idea what it's wrong with my code? Thanks.
<?php
if(isset($_POST['submitted']) == 1)
{
$title = mysqli_real_escape_string($dbc, $_POST['title']);
$header = mysqli_real_escape_string($dbc, $_POST['header']);
$body = mysqli_real_escape_string($dbc, $_POST['body']);
if(isset($_POST['id']) != 'null')
{
$q = "UPDATE pages SET user = $_POST[user], title = '$title', header = '$header', body = '$body' WHERE id = $_GET[id]";
}
else
{
$q = "INSERT INTO pages (user, title, header, body) VALUES ($_POST[user], '$title', '$header', '$body')";
}
$r = mysqli_query($dbc, $q);
if($r)
{
$message = '<p>Page was added!</p>';
}
else
{
$message = '<p>Page could not be added because:</p>'.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>

You are using post and get at the same time. first check whethet it is post or get. then just simply do isset() check
<?php
if(isset($_POST['submitted']) == 1)
{
$title = mysqli_real_escape_string($dbc, $_POST['title']);
$header = mysqli_real_escape_string($dbc, $_POST['header']);
$body = mysqli_real_escape_string($dbc, $_POST['body']);
if(isset($_GET['id']) && $_GET['id']!="")
{
$q = "UPDATE pages SET user = $_POST[user], title = '$title', header = '$header', body = '$body' WHERE id = $_GET[id]";
}
else
{
$q = "INSERT INTO pages (user, title, header, body) VALUES ($_POST[user], '$title', '$header', '$body')";
}
$r = mysqli_query($dbc, $q);
if($r)
{
$message = '<p>Page was added!</p>';
}
else
{
$message = '<p>Page could not be added because:</p>'.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>

Try this :
if(isset($_POST['id']) AND $_POST['id'] != 'null')

use this code: if(isset($_POST['id'] && $_POST['id']!= '')

Related

form have to click submit twice before success message in php

I am trying to do a reservation/booking page, so I have a form that gets information from the user and details about the services that they would like and add it to the database. I can insert records with no problems, like the record gets recorded only once and a success message if the data get inserted successfully and a fail message if otherwise should follow. The problem is the message would display after clicking the submit button twice or after the page refreshes.
This is how the code of the message looks:
if ($res_bookings){
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
And for the whole php code
<?php
//to get data from form
if(isset($_POST['submit'])){
//assign values
$customer_name = mysqli_real_escape_string($conn, $_POST['customer_name']);
$customer_number = mysqli_real_escape_string($conn ,$_POST['customer_number']);
$customer_email = mysqli_real_escape_string($conn, $_POST['customer_email']);
$event_type = mysqli_real_escape_string($conn, $_POST['event']);
$start = mysqli_real_escape_string($conn, $_POST['event_start']);
$end = mysqli_real_escape_string($conn, $_POST['event_end']);
$address = mysqli_real_escape_string($conn, $_POST['event_address']);
$menus = $_POST['menu'];
$extras = $_POST['extra'];
$booking_id = rand(000, 999);
$event_id = rand(000, 999);
$payment_id = rand(000, 999);
//no empty values to be inserted in database
if($customer_name == ""){
$_SESSION['name'] = "<p class='failed'>PLEASE FILL NAME</p>";
die();
}
if($customer_number == "" && $customer_email == ""){
$_SESSION['contacts'] = "<p class='failed'>PLEASE FILL CONTACTS</p>";
die();
}
if(empty($menus) || empty($extras)){
$_SESSION['menu'] = "<p class='failed'>PLEASE PICK YOUR MENU OR EXTRAS</p>";
die();
}
////for storing event details to event_details table
$query = "INSERT INTO event_details
SET id = ?,
startTime = ?,
endTime = ?,
eventAddress = ?,
event_type = (
SELECT id
FROM events
WHERE id = ?);";
$stmt = $conn->prepare($query);
$stmt->bind_param("isssi", $event_id, $start, $end, $address, $event_type);
$res_event = $stmt->execute();
if (!$res_event){
echo $conn->error;
}
//create booking record
$query_2 = "INSERT INTO bookings
SET id = ?,
customer_name = ?,
customer_contact_no = ?,
customer_email = ?,
eventID = (
SELECT id
FROM event_details
WHERE id = ?);";
$stmt_2 = $conn->prepare($query_2);
$stmt_2->bind_param("isssi", $booking_id, $customer_name, $customer_number, $customer_email, $event_id);
$res_book = $stmt_2->execute();
if (!$res_book){
echo $conn->error;
}
//create menu record
$menu_query = "INSERT INTO menus_bookings
SET
bookingID = (
SELECT id
FROM bookings
WHERE id = ?),
type = (
SELECT id
FROM menus_types
WHERE id = ?);";
$menu_stmt = $conn->prepare($menu_query);
$menu_stmt->bind_param("ii", $booking_id, $menu);
foreach ($menus as $menu){
$res_menu = $menu_stmt->execute();
}
if(!$res_menu){
echo $conn->error;
}
///create extras record
$extras_query = "INSERT INTO extras_bookings
SET
bookingID = (
SELECT id
FROM bookings
WHERE id = ?),
type = (
SELECT id
FROM extras_types
WHERE id = ?);";
$extras_stmt = $conn->prepare($extras_query);
$extras_stmt->bind_param("ii", $booking_id, $extra);
foreach ($extras as $extra){
$res_extras = $extras_stmt->execute();
}
if(!$res_extras){
echo $conn->error;
}
//calculate fees
$menu_sql = "SELECT SUM(mt.price) as 'menu total'
FROM menus_types mt, menus_bookings mb
WHERE mt.id = mb.type
AND mb.bookingID = ?;";
$stmt_menu = $conn->prepare($menu_sql);
$stmt_menu->bind_param("i", $booking_id);
$stmt_menu->execute();
$result_menu = $stmt_menu->get_result();
$row_menu = $result_menu->fetch_assoc();
$menu_total = $row_menu['menu total'];
$extras_sql = "SELECT SUM(et.price) as 'extras total'
FROM extras_types et, extras_bookings eb
WHERE et.id = eb.type
AND eb.bookingID = ?;";
$stmt_extras = $conn->prepare($extras_sql);
$stmt_extras->bind_param("i", $booking_id);
$stmt_extras->execute();
$result_extras = $stmt_extras->get_result();
$row_extras = $result_extras->fetch_assoc();
$extras_total = $row_extras['extras total'];
$total = $menu_total + $extras_total;
$min = $total * .50;
//create payment details
$query_pay = "INSERT INTO payment_details
SET id = ?,
extras_total = ?,
menus_total = ?,
total = ?,
minPayment = ?;
";
$stmt_pay = $conn->prepare($query_pay);
$stmt_pay->bind_param("iiiii", $payment_id, $extras_total, $menu_total, $total, $min);
$res_pay = $stmt_pay->execute();
if(!$res_pay){
echo $conn->error;
}
//add receipt to booking record
$query_booking = "UPDATE bookings
SET receiptID = (
SELECT id
FROM payment_details
WHERE id = ?)
WHERE id = ?;
";
$stmt_bookings = $conn->prepare($query_booking);
$stmt_bookings->bind_param("ii", $payment_id, $booking_id);
$res_bookings = $stmt_bookings->execute();
if ($res_bookings){
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
}
?>
I am not used to using PHP at all, but I think the issue is in the PHP part and not in the HTML.
You are writing this data to the $_SESSION variable and not actually outputting it to the page.
If you wish to show the success message after the form is submitted just use:
if ($res_bookings) {
echo "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
echo "<h2 class='failed'>BOOKING FAILED</h2>";
}
change this last part of your code:
$stmt_bookings = $conn->prepare($query_booking);
$stmt_bookings->bind_param("ii", $payment_id, $booking_id);
$res_bookings = $stmt_bookings->execute();
if ($res_bookings){
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
}
to this :
$stmt_bookings = $conn->prepare($query_booking);
$stmt_bookings->bind_param("ii", $payment_id, $booking_id);
$res_bookings = $stmt_bookings->execute();
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
which means immediately after code execution, success message will be displayed else failed message appears.

php data on crud doesn't inserted

im making an insert function on php, everything is ok, there is no error but the data doesnt show up in the database, here is my php file
<?php
include 'koneksi/koneksi.php';
if(isset($_POST['Submit'])) {
$id_koperasi = $_POST['id'];
$nama_koperasi = $_POST['nama'];
$alamat = $_POST['alamat'];
$telp = $_POST['telp'];
$hp = $_POST['hp'];
$nama_cp = $_POST['kontak'];
$email = $_POST['email'];
$nama_cp = $_POST['kontak'];
$tanggal = $_POST['tgl'];
$ket_fu = $_POST['ket'];
$hasil_pembahasan = $_POST['hasil'];
$status = $_POST['stat'];
$query = "INSERT INTO t_koperasi(id,id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status) VALUES ('',
'$id_koperasi',
'$nama_koperasi',
'$alamat',
'$telp',
'$hp',
'$nama_cp',
'$tanggal',
'$ket_fu',
'$hasil_pembahasan',
'$status')"
;
if (mysqli_query($con,$query)) {
header("location:index.php");
}else {
error_log( "This code has errors!" );
}
}
include 'views/v_form.php';
?>
and this is my database t_koperasi structure
The id is auto increasing, so you should remove id column in you insert sql. Also, the method you are using is dangerous, you should not totally trust what pass to you by other users in you website page, instead, you need to add filter functions.
You Query Should Look Like this. At Least in postgresql and MySql
$query = "INSERT INTO t_koperasi(id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status) VALUES (
'".$id_koperasi."',
'".$nama_koperasi."',
'".$alamat."',
'".$telp."',
'".$hp."',
'".$nama_cp."',
'".$tanggal."',
'".$ket_fu."',
'".$hasil_pembahasan."',
'".$status."')"
;
You do not need to insert value into ID .Because ID expected to be the primary key with default value (auto increment).
Hope This works for you!
Simple remove id and ' ' . i hope work fine.
or
You just copy this code and past your project
<?php
include 'koneksi/koneksi.php';
if(isset($_POST['Submit'])) {
$id_koperasi = $_POST['id'];
$nama_koperasi = $_POST['nama'];
$alamat = $_POST['alamat'];
$telp = $_POST['telp'];
$hp = $_POST['hp'];
$nama_cp = $_POST['kontak'];
$email = $_POST['email'];
$nama_cp = $_POST['kontak'];
$tanggal = $_POST['tgl'];
$ket_fu = $_POST['ket'];
$hasil_pembahasan = $_POST['hasil'];
$status = $_POST['stat'];
$query = "INSERT INTO t_koperasi(id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status) VALUES ('$id_koperasi',
'$nama_koperasi',
'$alamat',
'$telp',
'$hp',
'$nama_cp',
'$tanggal',
'$ket_fu',
'$hasil_pembahasan',
'$status')"
;
if (mysqli_query($con,$query)) {
header("location:index.php");
}else {
error_log( "This code has errors!" );
}
} include 'views/v_form.php';

how to solve unknown column error in mysql

I was working on a forum script when i encounter this error
Notice: Undefined variable: userids in
C:\xampp\htdocs\myfolder\discussion\post_reply_parse.php on line 19
Unknown column 'email' in 'field list'
Please, help me. This is the code
<?php
session_start();
if ($_SESSION['uid']) {
if (isset($_POST['reply_submit'])) {
include_once("connect.php");
$creator = $_SESSION['uid'];
$cid = $_POST['cid'];
$tid = $_POST['tid'];
$reply_content = $_POST['reply_content'];
$sql = "INSERT INTO posts (category_id, topic_id, post_creator, post_content, post_date) VALUES ('".$cid."', '".$tid."', '".$creator."', '".$reply_content."', now())";
$res = mysql_query($sql) or die(mysql_error());
$sql2 = "UPDATE categories SET last_post_date=now(), last_user_posted='".$creator."' WHERE id='".$cid."' LIMIT 1";
$res2 = mysql_query($sql2) or die(mysql_error());
$sql3 = "UPDATE topics SET topic_reply_date=now(), topic_last_user='".$creator."' WHERE id='".$tid."' LIMIT 1";
$res3 = mysql_query($sql3) or die(mysql_error());
$sql4 = "SELECT post_creator FROM posts WHERE category_id='".$cid."' AND topic_id='".$tid."' GROUP BY post_creator";
$res4 = mysql_query($sql4) or die(mysql_error());
while ($row4 = mysql_fetch_assoc($res4)) {
$userids[] .= $row4['post_creator'];
}
foreach ($userids as $key) {
$sql5 = "SELECT id, email FROM users WHERE id='".$key."' AND forum_notification='1' LIMIT 1";
$res5 = mysql_query($sql5) or die(mysql_error());
if (mysql_num_rows($res5) > 0) {
$row5 = mysql_fetch_assoc($res5);
if ($row5['id'] != $creator) {
$email .= $row5['email'].", ";
}
}
}
$email = substr($email, 0, (strlen($email) - 2));
$to = "noreply#somewhere.com";
$from = "YOUR_SITE_EMAIL_HERE";
$bcc = $email;
$subject = "YOUR_SUBJECT_HERE";
$message = "YOU MESSAGE CONTENT HERE";
$headers = "From: $from\r\nReply-To: $from";
$headers .= "\r\nBcc: {$bcc}";
mail($to, $subject, $message, $headers);
if (($res) && ($res2) && ($res3)) {
echo "<p>Your reply has been successfully posted. <a href='view_topic.php?cid=".$cid."&tid=".$tid."'>Click here to return to the topic.</a></p>";
} else {
echo "<p>There was a problem posting your reply. Try again later.</p>";
}
} else {
exit();
}
} else {
exit();
}
?>
Look at the structure of the users table and make sure you use the correct name for the column containing the email address. After that, remove the period on the line
$userids[] .= $row4['post_creator'];
...so it turns into:
$userids[] = $row4['post_creator'];

Checking for empty fields without using fetch

I am having some problems with checking if the field is empty or not in SQL using PHP without using mysql_fetch_array().
I have this code:
date_default_timezone_set('Asia/Taipei');
$remarks = $_POST['remarks'];
$date_added = date ("Y-m-d");
$time_added = date ("h:i:s a");
$lname = $_SESSION['user']['last_name'];
$fname = $_SESSION['user']['first_name'];
$minitial = $_SESSION['user']['middle_initial'];
$con = mysqli_connect("localhost", "root", "", "thisdb");
if(empty(`TIME_IN_1`)) {
$query = "INSERT INTO time_logs (LAST_NAME, FIRST_NAME, MIDDLE_INITIAL, DATE, TIME_IN_1, TIME_IN_1_REMARKS) VALUES('$lname', ' $fname', '$minitial', '$date_added', '$time_added', '$remarks')";
}
else {
$query = "UPDATE time_logs SET TIME_IN_2 = '$time_added' where LAST_NAME = '$lname' AND DATE = '$date_added'";
}
$save = mysqli_query($con, $query);
header("Location: time_in_complete.php");
What I basically want to accomplish is if the TIME_IN_1 field is empty, the data will be added there. If it is not empty, then the data will be added to the TIME_IN_2.
Apprently, this line:
if(empty(`TIME_IN_1`))
doesn't seem to work.
$first_query = "SELECT TIME_IN_1 FROM time_logs WHERE LAST_NAME = '" . $lname . "' AND FIRST_NAME = '" . $fname . "'";
$data = mysqli_query($con, $first_query);
$num_row = mysqli_num_rows($data);
if($num_row == 0) {
$query = "INSERT INTO time_logs (LAST_NAME, FIRST_NAME, MIDDLE_INITIAL, DATE, TIME_IN_1, TIME_IN_1_REMARKS) VALUES('$lname', ' $fname', '$minitial', '$date_added', '$time_added', '$remarks')";
}
else {
$query = "UPDATE time_logs SET TIME_IN_2 = '$time_added' where LAST_NAME = '$lname' AND DATE = '$date_added'";
}
$save = mysqli_query($con, $query);
header("Location: time_in_complete.php");
Try a query like:
SELECT TIME_IN_1 from time_logs where LAST_NAME = '$lname' AND DATE = '$date_added'
Then:
// Default to true and set this false if we find a value
$bIsEmpty = true;
// Check if any rows match
if ($result->num_rows > 0){
// Yes a row matches, so check if we have a value
$row = $result->fetch_object();
if ($row->TIME_IN_1 != "")
$bIsEmpty = false;
}
if ($bIsEmpty === true){
// Do your insert
} else {
// Do your update
}

How to submit a form and save to the database when some form fields are empty

I want some of my field leave it blank, for some proposes but form don't submit to the database if some input is blank.
form work fine if I have all values in the form fields but if there are one or two values blank all information not submit to the database.
<?php
if(isset($_POST['submit'])){
//process the form
$name = $_POST["name"];
$address = $_POST["address"];
$contact = $_POST["contact"];
$transaction = $_POST["transaction"];
$status = $_POST["status"];
$flemingia = $_POST["flemingia"];
$indigofera = $_POST["indigofera"];
$ipil_ipil = $_POST["ipil_ipil"];
$acid_ipil_ipil = $_POST["acid_ipil_ipil"];
$red_calliandra = $_POST["red_calliandra"];
$white_calliandra = $_POST["white_calliandra"];
$centrosema = $_POST["centrosema"];
$goat_manual = $_POST["goat_manual"];
$lbc_tracking = $_POST["lbc_tracking"];
$debit_amount = $_POST["debit_amount"];
$credit_amount = $_POST["credit_amount"];
$query = "INSERT INTO orders (";
$query .= "name, address, contact, transaction, flemingia, indigofera, ipil_ipil, acid_ipil_ipil, ";
$query .= "red_calliandra, white_calliandra, centrosema, goat_manual, lbc_tracking, debit_amount, credit_amount, status";
$query .= ") VALUES (";
$query .= "'{$name}', '{$address}', {$contact}, '{$transaction}', {$flemingia}, {$indigofera}, {$ipil_ipil}, {$acid_ipil_ipil}, ";
$query .= "{$red_calliandra}, {$white_calliandra}, {$centrosema}, {$goat_manual}, {$lbc_tracking}, {$debit_amount}, {$credit_amount}, {$status}";
$query .= ")";
$order_set = mysqli_query($connection, $query);
if($order_set){
redirect_to("orders.php");
} else{
$message = "order creation failed";
}
} else {
}
For each of your $_POST vars,
$name = (isset( $_POST['name'] )) ? $_POST['name'] : '';
This will set $name to an empty string if it doesn't exist.

Categories