Inserting data by PHP and MySQL - php

It's working, but when I add the data in to my database, the data will be twice. I don't know if my syntax is wrong or my code is wrong.
Here's the structure:
//if submit is clicked
$checkin = $_POST['text_checkin'];
while ($row = mysqli_fetch_array($reservation)) {
if (isset($_POST['submitBtn'])) {
if ($row['reservefrom'] == $checkin) {
echo "Same Date";
return;
}
else
{
$lastname = $_POST['text_lastname'];
$firstname = $_POST['text_firstname'];
$address = $_POST['text_address'];
$tnumber = $_POST['text_tnumber'];
$cnumber = $_POST['text_cnumber'];
$email = $_POST['text_email'];
$checkin = $_POST['text_checkin'];
$checkout = $_POST['text_checkout'];
$room = $_POST['text_room'];
$tour = $_POST['text_tour'];
$guest = $_POST['text_guest'];
$query = "INSERT INTO reservation
(lastname, firstname, homeaddress,
telephonenumber, cellphonenumber, email,
reservefrom, reserveto, room, tour,
guestnumber)
values ('$lastname', '$firstname', '$address',
'$tnumber', '$cnumber', '$email', '$checkin',
'$checkout', '$room', '$tour', '$guest')";
mysqli_query($db, $query);
echo "Data Submitted!";
}
}
}

You're getting multiple inserts because you are looping for each record in $reservations. You should first look into why you are getting multiple records if you expected just a single record reservation.
That aside, alter your code by replacing your while loop with:
if(isset($_POST['submitBtn']) && $row = mysqli_fetch_array($reservation)){
if($row['reservefrom'] == $checkin) die("Same Date");
$lastname = $_POST['text_lastname'];
$firstname = $_POST['text_firstname'];
// ... other values, then execute your query
}else{
// either submitBtn was not posted or no result were found in $reservation
}
I noticed also that you use return in your code, but the code doesn't seem to be within a function so that's confusing. If it is within a function, it's probably a bad idea to echo from within unless the function is specifically meant to send data directly to the browser.

Related

Error adding data in mysql table using PHP

I'm making a simple CURD operation using PHP and MYSQL. However I'm not able to insert/add data in the created table.
I think it might be a syntax error itself, but I can't figure out which one. The rest of the code works fine.
operation.php:
require_once("../CRUD/php/db.php");
$conn = createDB();
if(isset($_POST['create']))
{
createData();
}
function createData()
{
$name = textboxValue("name_type");
$age = textboxValue("age_type");
$gender = textboxValue("gender_type");
$email = textboxValue("email_type");
$contact = textboxValue("contact_type");
$dept = textboxValue("dept_type");
$sql = "INSERT INTO details(name,age,gender,email,contact,department)
VALUES('$name', '$age', '$gender', $email', '$contact', '$dept');";
if(mysqli_query($GLOBALS['conn'],$sql))
{
echo "Data added";
}
else
{
echo "Error adding data";
}
}
function textboxValue($value)
{
$textbox = mysqli_real_escape_string($GLOBALS['conn'], trim($_POST[$value]));
if(empty($textbox))
{
return false;
}
else
{
return $textbox;
}
}
"Error adding data" gets echoed. I can share the html code as well if needed.
$sql = "INSERT INTO details(name,age,gender,email,contact,department)
VALUES(\"$name\", \"$age\", \"$gender\", \"$email\", \"$contact\", \"$dept\");";
and so? By the way one quote you forgot near $email

Adding date, time and foreign key values from user input into mysql db?

I have the below code that should add user input into the db, I can't understand why its not adding to db, the email field in the table is a foreign key that references to another table, and I'm using session to store email in the $email and save it to db when user saves data, also I'm accepting date and time from user input which is exactly as per the db format but it still doesn't save, I have tried entering static data as well, not working either. Am I missing something ?
$server = "localhost";
$user = "root";
$pwd = "";
$sql_db = "cabcustomers";
$email = $_SESSION['sesName'];
$conn = #mysqli_connect($server,$user,$pwd,$sql_db);
if (isset ($_POST["name"]) && isset ($_POST["contact"]) && isset ($_POST["unitno"]) && isset ($_POST["streetno"]) && isset ($_POST["streetname"]) && isset ($_POST["suburb"]) && isset ($_POST["destsuburb"]) && isset ($_POST["pickdt"]) && isset ($_POST["picktime"]))
{
$name = $_POST["name"];
$contact = $_POST["contact"];
$unitno = $_POST["unitno"];
$streetno = $_POST["streetno"];
$streetname = $_POST["streetname"];
$suburb = $_POST["suburb"];
$destsuburb = $_POST["destsuburb"];
$pickdt = $_POST["pickdt"];
$picktime = $_POST["picktime"];
if(empty($name) || empty($contact) || empty($unitno) || empty($streetno) || empty($streetname) || empty($suburb) || empty($destsuburb) || empty($pickdt) || empty($picktime))
{
echo "<p>ONE OR MORE OF FIELDS HAVE MISSING INFORMATION, KINDLY CHECK AND TRY AGAIN!</p>";
}
elseif (!is_numeric($contact))
{
echo "<p>CONTACT NUMBER MUST BE NUMERIC!</p>";
}
else
{
$idlen = 7;
$bookingid = uniqid (rand(), true);
$bookingid = "BK" . substr($bookingid, 0, $idlen);
$status = "unassigned";
$pickdt = $pickdt . " " . $picktime;
$query = "insert into bookings (bookingid, pname, contact, unitno, streetno, streetname, suburb, destsuburb, pickupdt, bookingdt, status, email) values ('$bookingid', '$name', '$contact', '$unitno', '$streetno', '$streetname', '$suburb', '$destsuburb','$pickdt', 'NOW()','$status', '$email');";
echo $email;
$result = mysqli_query($conn, $query);
echo $result;
echo "<p>INFORMATION SAVED</p>";
}
mysqli_close($conn);
}
Based on the comments after your initial question, I don't think the connection is the problem, the problem is most likely happening during the INSERT query. Have you tried running the query from phpMyAdmin to troubleshoot the syntax of the query outside of PHP?

PHP Form Posts to MySQL Database Successfully, But Adds Blank Rows sometimes when registering

PHP Form Posts to MySQL Database Successfully, But Adds Blank Rows sometimes when registering.
here is my code:
include("includes/db.php");
if (isset($_POST['submit']) && $hidden == "" ) {
$product = mysqli_real_escape_string($bd, $_POST['product']);
$name = mysqli_real_escape_string($bd, $_POST['name']);
$address = mysqli_real_escape_string($bd, $_POST['address']);
$coupon = mysqli_real_escape_string($bd, $_POST['coupon']);
date_default_timezone_set("Asia/Kolkata");
$dates = date('Y-m-d H:i:s');
if (isset($_FILES["invoice_copy"]["name"])) {
$imgpancard = $_FILES["invoice_copy"]["name"];
$tmp_name = $_FILES['invoice_copy']['tmp_name'];
$error = $_FILES['invoice_copy']['error'];
if (!empty($imgpancard)) {
$location = 'doc/';
if (move_uploaded_file($tmp_name, $location.$imgpancard)){
//echo 'Uploaded';
}
}
}
$query = mysqli_query($bd, "SELECT * FROM customer WHERE coupon='".$coupon."'");
if(mysqli_num_rows($query) > 0) {
echo'<script> alert("COUPON ALEARDY EXISTS!");
window.location="register.php";
</script> ';
}
else {
$sql = "INSERT INTO customer (product, customer_name, address, coupon, RegistrationDate, invoice_copy) VALUES ('$product', '$name', '$address', '$coupon', '$dates', '$imgpancard')";
if(mysqli_query($bd, $sql)){
echo'<script> alert("DATA SUBMITTED SUCCESFULLY!");
window.location="index.html"; </script> ';
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($bd);
}
}
}
how to of 10 times one times blank data is inserted.how to avoid it can please tell me , whether code is wrong or not. In every input feild i have used required attribute

Array objects not being printed in input fields and sql query not receiving the id value

I am getting the id from another page but i am not being able to pass it to the sql query. If i define any value to $id instead of 0 then the query works but otherwise it fails.
Secondly, i would like to display the values of the array in respective input fields. I tried using
<?php
echo $result_array['institutename'][0];
?>
in the body part but it didnt work out.
My rest code is as follows:
(I know the mysql functions are deprecated but i would move on to mysqli as soon as i have solved this problem)
<?php
include 'connect.php';
$id=0;
$result_array=array();
if(isset($_REQUEST['id'])){
$id=(int)$_REQUEST['id'];
//$uid=$id;
if(!empty($id)){
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$result_array[]=$row;
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form_institutedetails'] == 'saveinstitutedetails')
{
$mysql_table='institute';
$institutename = $_POST['institutename'];
$established = $_POST['established'];
$regno = $_POST['reg_no'];
$branch = $_POST['branch'];
$initials = $_POST['initials'];
$address=$_POST['address'];
$pin=$_POST['pin'];
$contact1=$_POST['contact1'];
$contact2=$_POST['contact2'];
$contact3=$_POST['contact3'];
$fax1=$_POST['fax1'];
$fax2=$_POST['fax2'];
$email=$_POST['email'];
$website=$_POST['website'];
if(isset($_POST['head_office'])){
$head_office=$_POST['head_office'];
}
else{
$head_office="Branch";
}
if (!preg_match("/^.+#.+\..+$/", $email))
{
$error_message = 'Email is not a valid email address. Please check and try again.';
}
if (empty($error_message))
{
$newinstitutename = mysql_real_escape_string($institutename);
$newestablished = mysql_real_escape_string($established);
$newregno = mysql_real_escape_string($regno);
$newbranch = mysql_real_escape_string($branch);
$newaddress = mysql_real_escape_string($address);
$newpin = mysql_real_escape_string($pin);
$newemail = mysql_real_escape_string($email);
$newwebsite = mysql_real_escape_string($website);
$ho = mysql_real_escape_string($head_office);
include 'connect.php';
$sql = "UPDATE `".$mysql_table."` SET `institutename`='$newinstitutename', `established`='$newestablished', `regno`='$newregno', `branch`='$newbranch', `initials`='$initials', `address`='$newaddress', `pin`='$newpin', `contact1`='$contact1', `contact2`='$contact2', `contact3`='$contact3', `fax1`='$fax1', `fax2`='$fax2', `email`='$newemail', `website`='$newwebsite', `head_office`='$ho' WHERE `id`=$id";
$result = mysql_query($sql, $db);
mysql_close($db);
$error_message='Updated Successfully!.';
}
}
?>
When you are unsure about the structure of an array, you can always do a print_r during development.
print_r($result_array);
In this case, it is an index array of associative arrays.
To access the first record's institutename (and probably the only record since it looks like you used an unique key in your query), you can use
echo $result_array[0]['institutename'];

Cannot execute sql INSERT query (mysql_query) in php script. PHP/MySQL -- Time Sensitive

UPDATE: NOW RESOLVED - Thanks everyone!
Fix: I had a column named "referred_by" and in my code it's called "referred_by_id" - so it was trying to INSERT to a column that didn't exist -- once I fixed this, it decided to work!
I have limited time left to work on this project. The clock is ticking.
I'm trying to INSERT $php_variables into a TABLE called "clients".
I've been trying for hours to get this script to work, and I got it to work once, but then I realized I forgot a field, so I had to add another column to the TABLE and when I updated the script it stopped working. I reverted by but now it's still not working and I'm just frustrating myself too much.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (!isset($_COOKIE["user"]))
{
header ("Location: ./login.php");
}
else
{
include ("./source.php");
echo $doctype;
}
$birthday = $birth_year . "-" . $birth_month . "-" . $birth_day;
$join_date = date("Y-m-d");
$error_type = 0;
$link = mysql_connect("SERVER", "USERNAME", "PASSWORD");
if (!$link)
{
$error = "Cannot connect to MySQL.";
$error_type = 1;
}
$select_db = mysql_select_db("DATABASE", $link);
if (!$select_db)
{
$error = "Cannot connect to Database.";
$error_type = 2;
}
if ($referred_by != "")
{
$result = mysql_query("
SELECT id FROM clients WHERE referral_code = $referred_by
");
if (!$result)
{
$error = "Cannot find referral.";
$error_type = 3;
}
while ($row = mysql_fetch_array($result))
{
$referred_by_id = $row['id'];
}
}
else
{
$referred_by_id = 0;
}
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$birth_month = mysql_real_escape_string($_POST['birth_month']);
$birth_day = mysql_real_escape_string($_POST['birth_day']);
$birth_year = mysql_real_escape_string($_POST['birth_year']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip_code = mysql_real_escape_string($_POST['zip_code']);
$phone_home = mysql_real_escape_string($_POST['phone_home']);
$phone_cell = mysql_real_escape_string($_POST['phone_cell']);
$referral_code = mysql_real_escape_string($_POST['referral_code']);
$referred_by = mysql_real_escape_string($_POST['referred_by']);
$organization = mysql_real_escape_string($_POST['organization']);
$gov_type = mysql_real_escape_string($_POST['gov_type']);
$gov_code = mysql_real_escape_string($_POST['gov_code']);
$test_query = mysql_query
("
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."')
");
if (!$test_query)
{
die(mysql_error($link));
}
if ($error_type > 0)
{
$title_name = "Error";
}
if ($error_type == 0)
{
$title_name = "Success";
}
?>
<html>
<head>
<title><?php echo $title . " - " . $title_name; ?></title>
<?php echo $meta; ?>
<?php echo $style; ?>
</head>
<body>
<?php echo $logo; ?>
<?php echo $sublogo; ?>
<?php echo $nav; ?>
<div id="content">
<div id="main">
<span class="event_title"><?php echo $title_name; ?></span><br><br>
<?php
if ($error_type == 0)
{
echo "Client was added to the database successfully.";
}
else
{
echo $error;
}
?>
</div>
<?php echo $copyright ?>
</div>
</body>
</html>
Definitely not working as is. Looks you have a 500 error, since you have an else with a missing if:
else
{
$referred_by_id = 0;
}
Otherwise, you'll need to post your DB schema.
Also, note that you're really taking the long way around with this code, which makes it difficult to read & maintain. You're also missing any sort of checks for SQL injection... you really need to pass things through mysql_real_escape_string (and really, you should use mysqli, since the mysql interface was basically deprecated years ago).
$keys = array('first_name',
'last_name',
'birthday',
'join_date',
'email',
'address',
'city',
'state',
'zip_code',
'phone_home',
'phone_cell',
'referral_code',
'referred_by_id',
'organization',
'gov_type',
'gov_code');
$_REQUEST['birthdate'] = $_REQUEST['birth_year'].'-'.$_REQUEST['birth_month'].'-'.$_REQUEST['birth_day'];
$_REQUEST['join_date'] = date('Y-m-d',time());
$params = array();
foreach ($keys as $key)
{
$params[] = mysql_real_escape_string($request[$key]);
}
$sql = 'INSERT INTO clients ('.implode(',', $keys).') ';
$sql .= ' VALUES (\''.implode('\',\'', $params).'\') ';
You've an error on line 81:
else
{
$referred_by_id = 0;
}
I don't see an IF construct before that, make the appropriate correction and run the script again.
Without looking at the table structure to make sure all the fields are there, I'm going to assume it's something with the data.
Any quotes in the data will lead to problems (including SQL injection security holes). You should wrap each $_POST[] with mysql_real_escape_string(), such as:
$first_name = mysql_real_escape_string($_POST['first_name']);
EDIT: Further debugging...
As someone suggested (sorry, can't find the comment), try:
$sql = "
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."'
)";
// Debug:
print "<pre>". $sql ."</pre>";
mysql_query($sql);
The SQL statement should be printed out when submitting the form. Take that SQL statement and try to execute it directly in MySQL to see if it works, or if it generates an error.

Categories