CodeIgniter not properly inserting sql data - php

$idgen = uniqid(rand(), false);
$churchName = $this->input->post('church_name');
$streetAddress = $this->input->post('street_address');
$locationalCity = $this->input->post('locational_city');
$locationalState = $this->input->post('locational_state');
$locationalZip = $this->input->post('locational_zip');
$locationalCountry = $this->input->post('locational_country');
$taxNum = $this->input->post('tax_exemption_number');**
$this->db->query("INSERT INTO church_repo (church_name, street_address, locational_address, locational_zip, locational_country, locational_city, overseer_account_id, tax_exemption_number, status) VALUES('{$churchName}', '{$streetAddress}', '{$locationalCity}', '{$idgen}', '{$locationalState}', '{$locationalZip}', '{$locationalCountry}', '{$taxNum}', 'pending')");
The code above isn't inserting correctly, in Ci I'm getting the following error:
Error Number: 1054Unknown column 'locational_address' in 'field
list'INSERT INTO church_repo (church_name, street_address,
locational_address, locational_zip, locational_country,
locational_city, overseer_account_id, tax_exemption_number, status)
VALUES('bgtg', 'ff', 'rgfr', '270284f1eec6e5bfd4', 'rgrd', 'bdtbdt',
'United States of America', '84894894894', 'pending')Filename:
C:\Workspace\htdocs\Jan-2012\Gospel-links.org\system\database\DB_driver.phpLine
Number: 330

check your table attribute names, that error means that "locational_address" doesn't exist in your table. may be just a typo

The error is self-explanatory: there's no "locational_address" field, as already pointed out by d2byrke, so you should start by checking that.
Might be "street_address", maybe?
As an addendum, you're not escaping the values you enter in your DB; use query bindings, if you don't want to use Active Record:
$churchName = $this->input->post('church_name');
$streetAddress = $this->input->post('street_address');
$locationalCity = $this->input->post('locational_city');
$locationalState = $this->input->post('locational_state');
$locationalZip = $this->input->post('locational_zip');
$locationalCountry = $this->input->post('locational_country');
$taxNum = $this->input->post('tax_exemption_number');
$sql = "INSERT INTO church_repo(church_name, street_address, locational_address, locational_zip, locational_country, locational_city, overseer_account_id, tax_exemption_number, status) VALUES(?,?,?,?,?,?,?,?,?)";
$this->db->query($sql, array($churchName,$streetAddress,$locationalCity,$locationalState,$locationalZip,$locationalChurch,$taxnum,'pending');
Or, even cleaner (and protected) with Active Record:
$field['church_name'] = $this->input->post('church_name');
$field['street_address'] = $this->input->post('street_address');
$field['locational_city'] = $this->input->post('locational_city');
$field['locational_state'] = $this->input->post('locational_state');
$field['locational_zip'] = $this->input->post('locational_zip');
$field['locational_country'] = $this->input->post('locational_country');
$field['tax_exemption_num'] = $this->input->post('tax_exemption_number');
$field['status'] = 'pending';
$field['overseer_account_id'] = 'value here';
$this->db->insert('church_repo', $field);
Where $field is an array with table names as index, and field values as value.

You need to be sanitizing/escaping that content you are inserting. If there is a ' or something else you'll hit an error. Make sure your DB really does contain locational_address. Copy/paste to make sure no typos.
I would consider changing to this, it's much easier to read and follow whats happening. And the data is properly escaped then.
$data = array(
'church_name' => $this->input->post('church_name'),
'street_address' => $this->input->post('street_address'),
.....
'tax_exemption_number' => $this->input->post('tax_exemption_number')
);
$this->db->insert('church_repo', $data);

Try this just changed the order or insert to mach with column
$idgen = uniqid(rand(), false);
$churchName = $this->input->post('church_name');
$streetAddress = $this->input->post('street_address');
$locationalCity = $this->input->post('locational_city');
$locationalState = $this->input->post('locational_state');
$locationalZip = $this->input->post('locational_zip');
$locationalCountry = $this->input->post('locational_country');
$taxNum = $this->input->post('tax_exemption_number');**
$this->db->query("INSERT INTO church_repo (church_name, street_address, locational_address, locational_zip, locational_country, locational_city, overseer_account_id, tax_exemption_number, status) VALUES('{$churchName}', '{$streetAddress}', '{$locationalCity}', '{$locationalZip}', '{$locationalState}', '{$locationalCountry}', '{$idgen}', '{$taxNum}', 'pending')");

Related

I am using php to insert fields into an MySq table. My newest php script is failing with the following error [duplicate]

This question already has answers here:
Can a table field contain a hyphen?
(2 answers)
Closed 6 years ago.
The error is:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '360-16s (pa_name, hd1, hd1_c, sf2, sf2_c, cc3, cc3_c, l4, l4_c, dsd5, dsd5_c, mt' at line 1
The script is:
<?php
include("../Includes/e360Vars.php");
include("../Includes/dbOpen1.php");
$pa_name = mysql_real_escape_string($_POST['pa_name']);
$hd1 = mysql_real_escape_string($_POST['hd1']);
$hd1_c = mysql_real_escape_string($_POST['hd1_c']);
$sf2 = mysql_real_escape_string($_POST['sf2']);
$sf2_c = mysql_real_escape_string($_POST['sf2_c']);
$cc3 = mysql_real_escape_string($_POST['cc3']);
$cc3_c = mysql_real_escape_string($_POST['cc3_c']);
$l4 = mysql_real_escape_string($_POST['l4']);
$l4_c = mysql_real_escape_string($_POST['l4_c']);
$dsd5 = mysql_real_escape_string($_POST['dsd5']);
$dsd5_c = mysql_real_escape_string($_POST['dsd5_c']);
$mt6 = mysql_real_escape_string($_POST['mt6']);
$mt6_c = mysql_real_escape_string($_POST['mt6_c']);
$p_p7 = mysql_real_escape_string($_POST['p_p7']);
$p_p7_c = mysql_real_escape_string($_POST['p_p7_c']);
$ip8 = mysql_real_escape_string($_POST['ip8']);
$ip8_c = mysql_real_escape_string($_POST['ip8_c']);
$m_i9 = mysql_real_escape_string($_POST['m_i9']);
$m_i9_c = mysql_real_escape_string($_POST['m_i9_c']);
$act10 = mysql_real_escape_string($_POST['act10']);
$act10_c = mysql_real_escape_string($_POST['act10_c']);
$gf11 = mysql_real_escape_string($_POST['gf11']);
$gf11_c = mysql_real_escape_string($_POST['gf11_c']);
$i12 = mysql_real_escape_string($_POST['i12']);
$i12_c = mysql_real_escape_string($_POST['i12_c']);
$isp13 = mysql_real_escape_string($_POST['isp13']);
$isp13_c = mysql_real_escape_string($_POST['isp13_c']);
$se14 = mysql_real_escape_string($_POST['se14']);
$se14_c = mysql_real_escape_string($_POST['se14_c']);
$br15 = mysql_real_escape_string($_POST['br15']);
$br15_c = mysql_real_escape_string($_POST['br15_c']);
$paos16 = mysql_real_escape_string($_POST['paos16']);
$paos16_c = mysql_real_escape_string($_POST['paos16_c']);
$sob17 = mysql_real_escape_string($_POST['sob17']);
$sob17_c = mysql_real_escape_string($_POST['sob17_c']);
$cs18 = mysql_real_escape_string($_POST['cs18']);
$cs18_c = mysql_real_escape_string($_POST['cs18_c']);
$ms19 = mysql_real_escape_string($_POST['ms19']);
$ms19_c = mysql_real_escape_string($_POST['ms19_c']);
$ate20 = mysql_real_escape_string($_POST['ate20']);
$ate20_c = mysql_real_escape_string($_POST['ate20_c']);
$sywtww21 = mysql_real_escape_string($_POST['sywtww21']);
$sywtww21_c = mysql_real_escape_string($_POST['sywtww21_c']);
$name2 = mysql_real_escape_string($_POST['Name2']);
$position = mysql_real_escape_string($_POST['Position']);
$sql = "INSERT INTO 360-16s (pa_name, hd1, hd1_c, sf2, sf2_c, cc3, cc3_c, l4, l4_c, dsd5, dsd5_c, mt6, mt6_c, p_p7, p_p7_c ,ip8, ip8_c, m_i9,
m_i9_c, atc10, atc10_c, gf11, gf11_c, i12, i12_c, isp13, isp13_c, se14, se14_c, br15, br15_c,paos16, paos16_c, sob17, sob17_c, cs18, cs18_c,
ms19, ms19_c, ate20, ate20_c, sywtww21, sywtww21_c, name2, position) VALUES ('$pa_name', '$hd1', '$hd1_c', '$sf2', '$sf2_c', '$cc3', '$cc3_c',
'$l4', '$l4_c', '$dsd5', '$dsd5_c', '$mt6', '$mt6_c', '$p_p7', '$p_p7_c', '$ip8', '$ip8_c', '$m_i9', '$m_i9_c', '$atc10', '$atc10_c', '$gf11',
'$gf11_c', '$i12', '$i12_c','$isp13', '$isp13_c', '$se14', '$se14_c', '$br15', '$br15_c', '$paos16', '$paos16_c', '$sob17', '$cs18', '$cs18_c',
'$ms19', '$ms19_c', '$ate20', '$sywtww21', '$sywtww21_c', '$name2', '$position')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
I have been unable to locate the problem area, so another set of eyes would help. And yes, I have attempted to use mysqli instead of MySQL however, this produces a different set of errors.
Any assistance would be appreciated.
Check your table name convention it must be like 360_16s
Read the naming convention, http://dev.mysql.com/doc/refman/5.7/en/identifiers.html.
Check your table name or try to rename from 360-16s to 360_16s then escape it 360_16s and also escape your mysql field
If you want to use the Table Name "360-16s" then you should escape the attribute name with ` characters
The Character - is an invalid Character for the Table Name, unless you escape it.
I suggest you wrap all columns and table names in these characters.
Example:
$sql = "INSERT INTO `360-16s` (`pa_name`, `hd1`...

Insert into multiple tables from one form (mysql and PHP)

I'm new to this site and coding so please go easy on me if you come across some rookie mistakes.
I have a single form that when submitted it inserts data into two separate tables (users, users_addresses). The user address should be linked back to the user by the User's ID.
I have seen a couple different methods that can be used for this type of problem (and none which IC an get to work), but I'm reaching out for help to see which would be the best way.
This is what I have so far:
public function createNewUser($details, $active)
{
$password = $details["password"];
$username = strtolower($details["username" ]);
$firstname = strtolower($details["firstname"]);
$lastname = strtolower($details["lastname" ]);
$email = strtolower($details["email" ]);
$sex = strtolower($details["sex" ]);
$datepicker = strtolower($details["datepicker" ]);
$disabled = ($active) ? "0" : "1";
$address1 = strtolower($details["address1" ]);
$address2 = strtolower($details["address2" ]);
$province = strtolower($details["province" ]);
$city = strtolower($details["city" ]);
$district = strtolower($details["district" ]);
$zipcode = strtolower($details["zipcode" ]);
$
$sql = "INSERT INTO users VALUES (NULL, LOWER('$username'), MD5('$password'), LOWER('$firstname'), LOWER('$lastname'), LOWER('$email'), LOWER('$sex'), LOWER('$datepicker'), 0, NOW(), $disabled, 0)";
$resultSet = $this->db->query($sql);
return $this->db->getInsertId();
$sql = "INSERT INTO users_addresses VALUES (NULL, LOWER('$userid'), LOWER('$address1'), LOWER('$address2'), LOWER('$province'), LOWER('$city'), LOWER('$district), LOWER('$zipcode')";
$resultSet = $this->db->query($sql);
return $this->db->getInsertId();
}
The second query is never executed as you have a return statement before it executing in all conditions. Even if that is corrected, $user_id in second query has not been filled with value obtained from first query. Solution is below:
First
return $this->db->getInsertId();
should be replaced by
$user_id=$this->db->getInsertId();
Second
return $this->db->getInsertId();
should be replaced by
return $user_id
There is quite something wrong / strange with your code:
Don't put variables directly in SQL code, use prepared statements instead.
You are calling strtolower and LOWER on all the data. No need to do it twice.
The second query is never done, because you return before it. That's "unreachable code".
The fix is probably done by replacing the first return $this->db->getInsertId() with $userid = $this->db->getInsertId() and the second one with return $userid.
Good luck and welcome to SO.

Shorter way of inserting form data into database?

I have a form that returns all of the below data
$name = $_POST['name'];
$description = $_POST['description'];
$type = $_POST['type'];
$env1 = $_POST['environment[com1]'];
$env2 = $_POST['environment[com2]'];
$env3 = $_POST['environment[com3]'];
$hltCode = $_POST['hlType[code]'];
$hltDB = $_POST['hlType[db]'];
$hltWCF = $_POST['hlType[wcf]'];
$tfsID = $_POST['tfsID'];
$release = $_POST['release'];
$createdBy = 'mhopkins';
$updatedBy = 'mhopkins';
This of course leads to a VERY long query like the following
$insertQuery = "INSERT INTO patches (name, description, type, com1, com2, bofa, code, db, wcf, tfsID, release, createdBy, updatedBy) VALUES ('".$name."','".$description."''".$type."','".$envCom1."','".$envCom2."','".$envBofA."','".$hltCode."','".$hltDB."','".$hltWCF."','".$tfsID."','".$release."','".$createdBy."','".$updatedBy."'")
$insertResult = $link->query($insertQuery);
The values section has a LOT of punctuation and many possibilities for typos. If I have my variable names be the same as the field columns, is there an easier/shorter way to do this?
Your code has sql injection vulnerabilities, I wouldn't run that code even from a trusted source.
You can try using an ORM like Idiorm, it will manage the column names and escape variables for you https://idiorm.readthedocs.org/en/latest/models.html?highlight=insert https://github.com/j4mie/idiorm/
require_once 'idiorm.php';
ORM::configure(array(
'connection_string' => 'mysql:host=localhost;dbname=my_database',
'username' => 'database_user',
'password' => 'top_secret'
));
$patch = ORM::for_table('patches')->create($_POST);
$patch->createdBy = 'mhopkins';
$patch->updatedBy = 'mhopkins';
$patch->save();
You could try to use variables to get the data out of $_POST and reuse them in the SQL string.
Like:
<?php
$descriptionFieldName = "description";
$description = $_POST[$descriptionFieldName];
$sql = "INSERT INTO patches ($descriptionFieldName) VALUES ($description);
?>
Not much shorter, well, even longer. Though this way you are only typing the form input name and the SQL column name once.
You can also try mapping an array to do the job for you, something like:
$dbColumnsToValues = array(
'column_1' => $_POST['column1'],
'column_2' => $_POST['column2'],
);
$columns = "'" . implode("',", array_keys($dbColumnsToValues)) . "'";
$values = "'" . implode("',", array_map(array($link, 'escape'), array_values($dbColumnsToValues))) . "'";
$sql = "INSERT INTO `some_table` (".$columns.") VALUES(".$values.")";
Not tested though, but you should get the point.
Also, assuming your $link object has an escape method that will make sure your input won't trigger an sql injection.
Lets assume that you have a table consisting of 3 columns: col0, col1, col2.
If you are inserting all the fields that are present in the table and in the same order, you can omit listing the column names in the query. Like instead of
INSERT INTO `table` (`col0`, `col1`, `col2`) VALUES ("{$val0}", "{$val1}", "{$val2}",);
try
INSERT INTO `table` VALUES ("{$val0}", "{$val1}", "{$val2}");
PS: PLease sanitize the variable values before using them in the query.

Insert into one table twice in same script?

I've asked this question before, but have changed my code since. I'm having trouble with this script which inserts form data into a table. The first insert creates a booking which stores the customer's contact details. The second insert takes the booking ref created in the first and creates a 'JOB' for the customer. The final insert is supposed to create a second 'JOB', the customer's return journey.
The first two inserts are running fine,
but it ignored the final one, the second JOB insert.
I have checked the table structures, and the data been passed to the script everything is okay, so the problem must be in the script (shown below) any help is greatly appreciated.
Is it correct to use one script to insert into the same table twice?
<?php
$customer_title = $_POST['customer_title'];
$customer_first_name = $_POST['customer_first_name'];
$customer_last_name = $_POST['customer_last_name'];
$billing_address = $_POST['billing_address'];
$customer_tel = $_POST['customer_tel'];
$customer_mobile = $_POST['customer_mobile'];
$customer_email = $_POST['customer_email'];
$passengers = $_POST['passengers'];
$cases = $_POST['cases'];
$return_flight_number = $_POST['return_flight_number'];
$price = $_POST['price'];
$pickup_date = $_POST['pickup_date'];
$pickup_time = $_POST['pickup_time'];
$pickup_address = $_POST['pickup_address'];
$destination_address = $_POST['pickup_destination'];
$return_date = $_POST['return_date'];
$return_time = $_POST['return_time'];
$return_pickup = $_POST['return_pickup'];
$return_destination = $_POST['return_destination'];
$booking_notes = $_POST['booking_notes'];
$booking_status = "Confirmed";
$authorised = "N";
$booking_agent = "ROOT_TEST";
$booking_date = date("Y/m/d");
if (isset($_POST['customer_title'])) {
include('../assets/db_connection.php');
$create_booking = $db->prepare("INSERT INTO bookings(customer_name, billing_address, contact_tel, contact_mob, contact_email, party_pax, party_cases, booking_notes, price, booking_agent, booking_date, booking_status, authorised)
VALUES(:customer_name, :billing_address, :contact_tel, :contact_mob, :contact_email, :party_pax, :party_cases, :booking_notes, :price, :booking_agent, :booking_date, :booking_status, :authorised );");
$create_booking->execute(array(
":customer_name" => $customer_title . ' ' . $customer_first_name . ' ' . $customer_last_name,
":billing_address" => $billing_address,
":contact_tel" => $customer_tel,
":contact_mob" => $customer_mobile,
":contact_email" => $customer_email,
":party_pax" => $passengers,
":party_cases" => $cases,
":booking_notes" => $booking_notes,
":price" => $price,
":booking_agent" => $booking_agent,
":booking_date" => $booking_date,
":booking_status" => $booking_status,
":authorised" => $authorised
));
$booking_ref = $db->lastInsertId('booking_ref'); // Takes Booking Ref generated in $create_booking
$scheduled = "N";
$create_job = $db->prepare("INSERT INTO jobs(booking_ref, pickup_date, pickup_time, pickup_address, destination_address, scheduled)
VALUES(:booking_ref, :pickup_date, :pickup_time, :pickup_address, :destination_address, :scheduled)");
$create_job->execute(array(
":booking_ref" => $booking_ref,
":pickup_date" => $pickup_date,
":pickup_time" => $pickup_time,
":pickup_address" => $pickup_address,
":destination_address" => $destination_address,
":scheduled" => $scheduled
));
$return = "Y";
$create_return = $db->prepare("INSERT INTO jobs(booking_ref, pickup_date, pickup_time, pickup_address, destination_address, scheduled, return)
VALUES(:booking_ref, :pickup_date, :pickup_time, :pickup_address, :destination_address, :scheduled, :return)");
$create_return->execute(array(
":booking_ref" => $booking_ref,
":pickup_date" => $return_date,
":pickup_time" => $return_time,
":pickup_address" => $return_pickup,
":destination_address" => $return_destination,
":scheduled" => $scheduled,
":return" => $return
));
}
?>
It is incorrect for sure, as inserting the same data twice violates one of most important database architecture laws - Database Normalization principle
However, there is no technical issues with it. There is some mistake which you have to catch using the error message from mysql. To have it, add this line after connecting to PDO.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Please note that catching the actual error is the only way to debug SQL queries. Just watching the code makes no sense nor help.
return must be a mysql keyword. write it as
`return`
By the way, I can't stand such enormously huge code.
If I were you, I'd make it in 10 lines, not 50:
$allowed = array('customer_name', 'billing_address', 'contact_tel', 'contact_mob',
'contact_email', 'party_pax', 'party_cases', 'booking_notes', 'price');
$insert = $db->filterArray($_POST,$allowed);
$insert['booking_status'] = "Confirmed";
$insert['authorised'] = "N";
$insert['booking_agent'] = "ROOT_TEST";
$insert['booking_date'] = date("Y-m-d");
$db->query("INSERT INTO bookings SET ?u", $insert);
It looks like booking_ref is the primary key in the jobs table, your trying to insert the same key twice which is why the final query fails.
You should have a seperate field that is the primary key on jobs which is just an auto-incrementing number, then create an index on booking_ref.
There's no law against it. What you need to do is check the return value for the last INSERT query. My best guess is there's a unique index on the jobs table that you're violating with the double-insert.
It's not obvious if you're using mySQLi or PDO here, but both's execute functions return false on failure, so you should catch that and then call the respective object's error functions to get what went wrong.

Insert Statement Problem

$lastname = clean($_SESSION['lastname']);
$firstname = clean($_SESSION['firstname']);
$mi = clean($_SESSION['mi']);
$nickname = clean($_SESSION['nickname']);
$studentno = clean ($_SESSION['studentno']);
$password = clean ($_SESSION['password']);
$cpassword = clean ($_SESSION['cpassword']);
$bdate = clean($_POST['bdate']);
$maddress = clean($_POST['maddress']);
$paddress = clean($_POST['paddress']);
$status = clean($_POST['status']);
$religion = clean($_POST['religion']);
$telno = clean($_POST['telno']);
$celno = clean($_POST['celno']);
$email = clean($_POST['email']);
$nationality = clean($_POST['nationality']);
$batch = clean($_POST['batch']);
$dept = clean($_POST['dept']);
$course = clean($_POST['course']);
$achvmnts = clean($_POST['achvmnts']);
$emp = clean($_POST['emp']);
$empadd = clean($_POST['empadd']);
$position = clean($_POST['position']);
$emptelno = clean($_POST['emptelno']);
$empemail = clean($_POST['empemail']);
I have the following INSERT query for the values above where the first 7 are being retrieved from a saved session, everything are declared as varchar except for the fields bdate = date, celno and studentno = bigint, :
$result = mysql_query("INSERT INTO `$dept`(lastname,firstname, mi,nickname,bdate,maddress,paddress,status,religion,telno,celno,email,nationality,password,studentno,batch,dept,course,achvmnts,emp,empadd,position) VALUES
('$lastname','$firstname','$mi','$nickname','$bdate', '$maddress','$paddress','$status,','$religion','$telno',$celno,'$email','$nationality','$password',$studentno,'$batch', '$dept','$course','$achvmnts','$emp','$empadd,'$position')");
.I can't seem to find the error in this query, for hours i have been receiving "Query Error". can anyone please help me find the error. Thanks in advance!
There is an error in your insert right there:
'$empadd, '$position')");
the 2. quotation is missing
$result = mysql_query("INSERT INTO `$dept`(lastname,firstname, mi,nickname,bdate,maddress,paddress,status,religion,telno,celno,email,nationality,password,studentno,batch,dept,course,achvmnts,emp,empadd,position) VALUES
('$lastname','$firstname','$mi','$nickname','$bdate', '$maddress','$paddress','$status','$religion','$telno',$celno,'$email','$nationality','$password',$studentno,'$batch', '$dept','$course','$achvmnts','$emp','$empadd','$position')");
Should work if thats the problem.
(Edit: removed the , in '$status,' since someone mentioned it in the comments
I don't believe you need the quotations on the INSERT INTO '$dept'. Also, I think your quotations are different, and $studentno has no quotations, I'm not sure if that was intentional. Last, could you post the exact query error
For one thing, this is a ridiculously huge INSERT to be making. Here are things I noted
'$status,', looks incorrect. This would add the status with a trialing comma
'$empadd, is missing a trailing quote
$celno is not placed within quotations. This is risky. All phone numbers should be stored as VARCHAR fields.
Consider using sprintf with mysql_real_escape_string in order to ensure that your variables are formatted correctly. For more information, consult the PHP manual docs on mysql_real_escape_string and sprintf.
The code could be a bit more readable and less open to errors resulting from repetition:
$session_columns = array('lastname','firstname','mi','nickname','studentno',
'password','cpassword');
$post_columns = array('bdate','maddress','paddress','status','religion','telno',
'celno','email','nationality','batch','dept','course','achvmnts','emp',
'empadd','position','emptelno','empemail');
$assignments = array();
foreach ($session_columns as $column)
$assignments[] = sprintf("$column = '%s'", clean($_SESSION[$column]));
foreach ($post_columns as $column)
$assignments[] = sprintf("$column = '%s'", clean($_POST[$column]));
$sql = "INSERT INTO `$dept` SET ".implode(', ', $assignments);

Categories