Insert Statement Problem - php

$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);

Related

Pass a PHP string in to SQL with multiple values?

I have a situation in some really old code of mine where I am trying to pass through the data from a string and do a DB query off of those values.
The data loads correctly if I set $hula = '7630' but when I set it to multiple values in a string like $hula = '7890, 5630' I get error (Message: db2_execute(): Statement Execute Failed)
I clearly know I am missing something here but I am CLEARLY not seeing it. Thanks
<?php
$hula = '7890, 5630';
$stmt = "SELECT TXLCT2, ZFDLDS FROM ".$ArEnviro>getDataLibFin().".TXPL6C2, ".
$ArEnviro->getDataLibFin().".HXPTABLD WHERE TXLCT2 = CFDECD AND CFDTCD = 'YCT2' AND TXLLV6 IN ? ORDER BY TXLCT2";
$preparedStmt = db_prepare($ArConnections->getDB2ConnResource(),$stmt);
$result = db_execute($preparedStmt, [$hula]);
while(($row = db_fetch_both($preparedStmt)) == true) {
echo('<option value="'.htmlspecialchars($row["TXLCT2"]).'">'.htmlspecialchars($row["TXLCT2"]).' - '.htmlspecialchars($row["ZFDLDS"]).'</option>');
}
?>
A simple change:
if TXLLV6 is integer:
$hula = '(7890, 5630)';
If it is varchar or any kind of string:
$hula = "('7890', '5630')";

SQL syntax error edit post

getting :
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 's Creed III', description='The plot is set in a fictional
history of real ' at line 2
when trying to edit posts on a database.
heres my display and edit php:
$result = mysql_query("SELECT * FROM gallery");
while ($row = mysql_fetch_array( $result )){
// while looping thru each record…
// output each field anyway you like
$title = $row['title'] ;
$description = $row['description'];
$year = $row['year'];
$rating = $row['rating'];
$genre = $row['genre'];
$filename = $row['filename'];
$imageid = $row['imageid'];
include '../modules/edit_display.html';
}
// STEP 2: IF Update button is pressed , THEN UPDATE DB with the changes posted
if(isset($_POST['submit'])){
$thisTitle = $_POST['title'];
$thisDescription = $_POST['description'];
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
$thisNewFilename = basename($_FILES['file']['name']);
$thisOneToEdit = $_POST['imageid'];
$thisfilename = $_POST['filename'];
if ($thisNewFilename == ""){
$thisNewFilename = $thisfilename ;
} else {
uploadImage();
createThumb($thisNewFilename , 120, "../uploads/thumbs120/");
}
$sql = "UPDATE gallery SET
title='$thisTitle',
description='$thisDescription',
year='$thisYear',
rating='$thisRating',
genre='$thisGenre',
filename='$thisNewFilename'
WHERE
imageid= $thisOneToEdit";
$result = mysql_query($sql) or die (mysql_error());
}
You're suffering from an imminent dose of SQL Injection due to using a dangerous user input model.
When you type "Assassin's Creed III" in the title field, that gets placed in single quotes in the UPDATE statement in your code (via the $_POST['title'] variable):
'Assassin's Creed III'
The problem there is that MySQL sees it as 'Assassin', followed by s Creed III'. It doesn't know what to do with the latter.
Of course, this becomes a HUGE problem if someone types in valid SQL at that point, but not what you expected. Have a look at How can I prevent SQL injection in PHP? or any of several other advices on avoiding SQL Injection.
i have seen you are adding ' into database so you need to escape it using addslashes()
addslashes($thisTitle)
You have syntax error here. Use $_POST instead of $POST.
Replace
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
With
$thisYear = $_POST['year'];
$thisRating = $_POST['rating'];
$thisGenre = $_POST['genre'];
you need to escape your input like
$thisDescription = mysql_real_escape_string($_POST['description']);
do this for all input that contains quotation marks etc..
NOTE: mysql will soon be gone so its advised to write new code using mysqli instead
You have alot of issues in your script.
You're trying to add ' character to database, you need to escape it properly with addslashes.
You're vulnerable to SQL Injection. Escape it properly with mysql_real_escape_string, or even better, use PDO.
Third, it is $_POST, not $POST. You're using it wrong in some areas.
Add quotes to $thisOneToEdit in query.
The error is causing because you're trying to add Assasin's Creed III string to database. The single quote breaks your query and creates a syntax error.
Do a addslashes() on the values that might contain single or double quotes like below before using them in query
$thisTitle = addslashes($_POST['title']);

Wrong mysql query in php file?

I'm trying to insert some data into my mysql database. The connection is working fine but im having a problem with sending the query correctly to the database. Below you can find the code in my php file. I also post what for type of fields they are in the Database.
Fields in the mysql database:
Reservaties_id = int
Materialen_id = int
aantal = int
effectief_gebruikt = tinyint
opmerking = Varchar2
datum_van = date
datum_tot = date
$resID = $_REQUEST['resID'];
$materialen_id = $_REQUEST['materialen_id'];
$aantal = $_REQUEST['aantal'];
$effectief_gebruikt = $_REQUEST['effectief_gebruikt'];
$opmerking = $_REQUEST['opmerking'];
$datum_van = date('YYYY-MM-DD',$_REQUEST['datum_van']);
$datum_tot = date('YYYY-MM-DD',$_REQUEST['datum_tot']);
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', $datum_van, $datum_tot)";
mysql_query($string);
you have to include single quotes for the date fields '$dataum_van'
$string = "INSERT INTO `materialen_per_reservatie`(reservaties_id, materialen_id, aantal, effectief_gebruikt, opmerking, datum_van, datum_tot) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')";
and this is only a example query, while implementing don't forget to sanitize your inputs
Your code has some serious problems that you should fix. For one, it is not doing any error checking, so it's no surprise the query breaks silently when it fails. Check for errors and it will tell you what goes wrong - how to do it is outlined in the manual on mysql_query() or in this reference question.. Example:
$result = mysql_query($string);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error(), E_USER_ERROR);
die();
}
In this specific case, I'm fairly sure it's because you are not putting your values into quotes after the VALUES keyword.
Also, the code you show is vulnerable to SQL injection. You need to escape every value you use like so:
$resID = mysql_real_escape_string($_REQUEST['resID']);
for this to work, you need to put every value in your query into quotes.
try this
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`) VALUES ('".$resID."')";

CodeIgniter not properly inserting sql data

$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')");

Using AND in Update clause - Mysql

My Code
$names = $_GET['name'];
$s = "update users set filelocation='$newname' where sessionusername = '$u' AND name = '$names'";
the above does not work, while the below works.
$s = "update users set filelocation='$newname' where sessionusername = '$u'";
How do i get it to work? every variable has a value that matches the database.
Thanks.
This is where I declare $names -
$names = mysqli_real_escape_string($connect, trim($_GET['name']));
echo $names;
ini_set('display_errors','On');
error_reporting(E_ALL);
if(isset($_POST['submitted'])){
Try to echo $s. This will output the query with the variabele values so you can check if there are any errors with these.
Plus use this this functions
mysql_real_escape_string
mysqli::real_escape_string

Categories