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
Related
Hi i am getting the problem of adding the record in to the database.when i insert the record into the database. message display record insert failed. i double checked the coding and programming syntax all were fine.but i didn't get any errors while was running what was the problem. can some one fix the problem do get the error. exception handing also i have put but unfortunate it doens't help for me to display the error.
<?php
if (isset($_POST['submit'])) {
$bassname = $_POST['bassname'];
$cat = $_POST['cat'];
$p_img1 = $_FILES['p_img1']['name'];
$p_img2 = $_FILES['p_img2']['name'];
$p_img3 = $_FILES['p_img3']['name'];
$temp_name1 = $_FILES['p_img1']['tmp_name'];
$temp_name2 = $_FILES['p_img2']['tmp_name'];
$temp_name3 = $_FILES['p_img3']['tmp_name'];
move_uploaded_file($temp_name1, "product_images/$p_img1");
move_uploaded_file($temp_name2, "product_images/$p_img2");
move_uploaded_file($temp_name3, "product_images/$p_img3");
$mobile = $_POST['mobile'];
$address = $_POST['address'];
$job_desc = $_POST['job_desc'];
$work_video = $_POST['work_video'];
$insert_product = "insert into
bass_registation(
bassname,
category,
job_image1,
job_image2,
job_image3,
mobile,
address,
job_des,
video
) values (
'$bassname',
'$cat',
'$p_img1',
'$p_img2',
'$p_img3',
'$mobile',
'$address',
'$job_desc',
'$work_video'
)";
$run_product = mysqli_query($con, $insert_product);
try {
if ($run_product) {
echo "<script>alert('Data has been inserted successfully')</script>";
} else {
echo "<script>alert('Data has been Failed')</script>";
}
}
catch (Exception $e) {
echo 'Message: ' . $e->getMessage();
}
}
?>
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.
So Ive been debugging this for a couple of hours and can't seem to work it out. Ive got a form that takes info into a session then from sessions it goes into a class.
form->session->class->database
Inside the class theres a function that looks like this:
function lagre($kunde)
{
$navn = $kunde->GetNavn();
$telefon = $kunde->GetTelefon();
$epost = $kunde->GetEpost();
$antall = $kunde->GetAntall();
$db = mysqli_connect("localhost","root","","Billett");
if($db->connect_error)
{
die("Couldn't connect");
}
else {
echo "Connected";
}
$sql = "INSERT INTO `Billett`.`Billett` (`BillettID`, `Navn`, `Telefon`, `Epost`, `Antall`) VALUES (NULL, '$navn', '$telefon', '$epost', '$antall')";
$resultat = mysqli_query($db,$sql);
if(!$resultat)
{
echo "<br> Values not inserted";
}
else {
echo "<br> Values inserted";
}
}
The problem is that the values doesn't insert into the database. I cant work out why. Any ideas?
You try to write in different way
$sql = "INSERT INTO `Billett`.`Billett` (`BillettID`, `Navn`, `Telefon`, `Epost`, `Antall`) VALUES (NULL, '".$navn."', '".$telefon."', '".$epost."', '".$antall."')";
Are you using Autocommit? If not then you need to commit your data to the DB, otherwise your INSERT doesn't stick:
/* commit transaction */
if (!$mysqli->commit()) {
print("Transaction commit failed\n");
exit();
}
Example from PHP documentation
final.php
Here I am trying to get the data from the url using GET method and trying to insert into the database. I was able to insert the data for first few rows after that the data is not inserted. Can anyone help me regarding this?
when I try to run the url: www.myii.com/app/final.php?name=123&glucose=3232...
the data is not inserting.
<?php
include("query_connect.php");
$name = $_GET['name'];
$glucose = $_GET['glucose'];
$temp = $_GET['temp'];
$battery = $_GET['battery'];
$tgs_a = $_GET['tgs_a'];
$tgs_g = $_GET['tgs_g'];
$heartrate = $_GET['heartrate'];
$spo2 = $_GET['spo2'];
$rr = $_GET['rr'];
$hb = $_GET['hb'];
$ina22 = $_GET['ina22'];
$accucheck = $_GET['accucheck'];
$isactive = $_GET['isactive'];
$address = $_GET['address'];
$deviceno = $_GET['deviceno'];
$sql_insert = "insert into query (name,glucose,temp,battery,tgs_a,tgs_g,heartrate,spo2,rr,hb,ina22,accucheck,isactive,address,deviceno) values ('$name','$glucose','$temp',$battery','$tgs_a','$tgs_g','$heartrate','$spo2','$rr','$hb','$ina22','$accucheck','$isactive','$address','$deviceno')";
mysqli_query($sql_insert);
if($sql_insert)
{
echo "Saving succeed";
//echo $date_time;
}
else{
echo "Error occured";
}
?>
Query_connect.php
This is my database config php file.
<?php
$user = "m33root";
$password = "me3i434";
$host = "localhost";
$connection = mysqli_connect($host,$user,$password);
$select = mysqli_select_db('miiyy',$connection);
if($connection)
{
echo "connection succesfull<br>";
}
else {
echo "Error";
}
?>
Make sure that all columns can contain NULL so that not filled fields will stay NULL instead of throwing an error.
Try below to see mysql error:
mysql_query($sql_insert);
echo mysql_error()
Try these
In SQL
Change the table name of query to some other name. Because "query" is reserved in SQL
In code
if (!mysqli_query($con,$sql_insert ))
{
echo("Error description: " . mysqli_error($con));
}
else
{
echo "Success";
}
Use mysqli_error() function
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.