I am working on a project that requires me to do a database insert with quite some columns to fill. I tried making my function dynamic so that I didn't have to type 28 insert into- columns, 28 placeholders, and then bind 28 values to 28 placeholders....and in the near future I might want to add more columns, so here's how I tried to set it up, the whole function and arrays are a bit to much to post here so I'll stick to the essential part with some psuedo code for my question:
-In my form, there are up to 28 inputs, and the input names are the same as the database column name
-The essential part of my code is as follows (some replaced by pseudo code to shorten this post)
<?php
//stacks holds 28 values in total
$stacks = array('name1','name2','name3','blablabla','etcetera');
// stacksDP is filled in a loop,
//contains the same as $stacks but it has a :
//in front of every value.
$stacksDP = array() // :name1',':name2', ....
$data = array(); // $data[stack / columnname] = "whatever";
$execArray = array();
//$execArray is filled like this in a foreach loop on $stacks as $stack:
//$execArray[$stacksDP[$stack]] = $data[$stack];
// so far so good, but now I want to make the actual query and the following gives me a "Syntax error or access violation: 1064 You have an error in your SQL syntax; "
$sql = "INSERT INTO stackoverflowplaceholder (".implode("','",$stacks)." VALUES (";
$sql .= implode(",",$stacksDP); // :columnname,
$sql .=")";
$q = $this->conn->prepare($sql);
echo $q->execute($execArray);
Any help on this matter would be appreciated :) Is it even possible what I'm trying to achieve here?
There is a missing, ), to close the column assignment, before the implode.
$sql = "INSERT INTO stackoverflowplaceholder (".implode("','",$stacks)." VALUES (";
will be
$sql = "INSERT INTO stackoverflowplaceholder (".implode("','",$stacks)." ) VALUES (";
Related
I'm currently trying to use the following PHP function/SQL query with a page that edits medications on a project I'm building for school. I'm getting the following error and having trouble to finding where the error is :
Syntax error or access violation: 1064 You have an error in your SQL syntax;
function edit_medicine($medicine_name, $medicine_dose, $medicine_date, $medicine_current, $medicine_id) {
global $db;
$query = "UPDATE Medicine
SET MedicineName = :medicine_name,
Medicine Dose = :medicine_dose,
MedicineDatePrescribed = :medicine_date,
MedicineCurrent = :medicine_current
WHERE MedicineKey = :medicine_id";
$statement = $db->prepare($query);
$statement->bindValue(':medicine_name', $medicine_name);
$statement->bindValue(':medicine_dose', $medicine_dose);
$statement->bindValue(':medicine_date', $medicine_date);
$statement->bindValue(':medicine_current', $medicine_current);
$statement->bindValue(':medicine_id', $medicine_id);
$statement->execute();
$statement->closeCursor();
}
I'd appreciate any help anyone can offer- it's the end of finals week and I'm totally burnt out. Thanks!
Use quote to your column names, especially your Medicine Dose column because of its space (). Next time, don't use space to name your columns:
$query = "UPDATE `Medicine`
SET `MedicineName` = :medicine_name,
`Medicine Dose` = :medicine_dose,
`MedicineDatePrescribed` = :medicine_date,
`MedicineCurrent` = :medicine_current
WHERE `MedicineKey` = :medicine_id";
If double quotes or backtick does not work , try including the string within square brackets.
For example
SELECT [Business Name],[Other Name] FROM your_Table
My entry form I have an inventory database with tables like aluminium, iron etc... Each table contains a subcategory of items like aluminium_pala, iron_1.5inch and so on. The entry code is like this:
include("dbConnect.php");
$orderNo = $_POST["number"];
if(isset($_POST["mat1"])&&$_POST["mat1"]!=NULL)
{
$mat1 = $_POST["mat1"];
$selmat1 = $_POST["selmat1"];
$amtmat1 = $_POST["amtmat1"];
$query = "INSERT INTO $mat1 ($selmat1,orderNo) VALUES (-$amtmat1,$orderNo);";
if(!($result = $mysqli->query($query)))
print "<div class='error'>insertion failed. Check your data</div>";
}
if(isset($_POST["mat2"])&&$_POST["mat2"]!=NULL)
{
$mat2 = $_POST["mat2"];
$selmat2 = $_POST["selmat2"];
$amtmat2 = $_POST["amtmat2"];
$query = "INSERT INTO $mat2 ($selmat2,orderNo) VALUES (-$amtmat1,$orderNo);";
if(!($result = $mysqli->query($query)))
print "<div class='error'>insertion failed. Check your data</div>";
}... and it goes on till mat11
I am trying to collect each similar table (mat1, mat2..) and their corresponding item (selmat1, selmat2...) and bunch the all in one query. That is, instead of going
INSERT INTO al_openable (zPala,orderNo) VALUES (23,14);
INSERT INTO al_openable (outer,orderNo) VALUES (50,14);
I am trying to execute it like
INSERT INTO al_openable (zPala,outer,orderNo) VALUES (23,50,14);
I need this to avoid duplicate foreign key entry(for $orderNo). One idea I've been considering is to use UPDATE if the order number is pre-existing. Do you guys think this is a good idea? And if so, what will be the best way to execute it? If not, how would a more experienced programmer solve this conundrum?
I think this question is related to your query: Multiple Updates in MySQL
You may use ON DUPLICATE KEY UPDATE in combination with INSERT statement.
I am inserting data from a excel sheet but i receive error and it looks like it is breaking because the value contain a space character in between. As far as i remember space characters allowed in VARCHAR(200)
This is the code i am using
//CREATE SQL QUERY FOR INSERTING DATA IN DATABASE
$sql = "INSERT INTO ".$month."_".$year."(";
foreach($sheetData[1] as $columnName){
$sql .= preg_replace('#[ ]#', '_',$columnName). ",";
}
$sql = rtrim($sql, ',');//REMOVES COMMA FROM END OF THE STRING
$sql .= ")";
//
$sql .= " VALUES((";
for($i=2;$i < count($sheetData);$i++){
foreach($sheetData[$i] as $columnName){
$sql .= $columnName.",";
}
$sql = rtrim($sql,',');//
$sql .= "),";
}
$sql = rtrim($sql,',');//
$sql .= ")";
echo $sql;
$query = mysqli_query($conn,$sql) or die(mysqli_error($conn));
After loops this is how my SQL QUERY look
INSERT INTO December_2015(S_No,Zone,State,City2,VM_Town,Distibutor_Code,Distributor_Name,Dealer_Code,Dealer_Name,Category,Address,Location,Contact,Mobile_No,Visit_1,Visit_2,Visit_3,Visit_4,Visit_5,Visit_6) VALUES( (1,South,Telanagana,Hyderabad,Y,1006704,Sai Santhoshi Enterprises,TG000999,Sree Laxmi Mobiles,A,F4,anthem Arcade,gujarathi Galli,koti ,Koti,Rajesh,8790575680,7-Nov,18-Nov,28-Nov))
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 'Santhoshi Enterprises,TG000999,Sree Laxmi Mobiles,A,F4,anthem Arcade,gujarathi G' at line 1
It says near 'Santhoshi Enterprises ... ' before that there is a space character
You have two "(" instead of one after "VALUES"
Akash,
Didn't you asked a question just a while ago regarding same/similar code with a different error you got, here at: How to loop inside a variable ?!
By the looks of it in general you write messy code, and you are having trouble reading/understanding the error messages. So I'm gonna guess you are new at this.
Here are some good reads for you:
Top 15+ Best Practices for Writing Super Readable Code
PHP the right way
When all said and done, here is your code broken down into more readable segments:
// prepare dummy data
$month = date('M');
$year = date('Y');
$sheetData = array(
array('data00', 'data01')
,array('col1', 'col2', 'col3', 'col4', 'col5', 'col6')
,array('data20', "data21")
,array('data30', 'data31')
,array('data40', 'data41')
);
// prepare vars
$tableName = "{$month}_{$year}";
$dataCount = count($sheetData);
// prepare columns
$columnsSQL = "";
foreach ($sheetData[1] as $columnName) {
// wrap with ` ticks
$columnsSQL .= '`'. preg_replace('#[ ]#', '_', $columnName).'`'.',';
}
$columnsSQL = rtrim($columnsSQL, ',');
// prepare values
$valuesSQL = "";
for ($i=2;$i < $dataCount;$i++) {
foreach($sheetData[$i] as $columnValue){
$valuesSQL .= "'{$columnValue}', ";
}
}
$valuesSQL = rtrim($valuesSQL, ', ');
$SQL = "
INSERT INTO {$tableName}( {$columnsSQL} )
VALUES ( {$valuesSQL} )";
At the end you end up with something like this:
INSERT INTO Nov_2015( `col1`,`col2`,`col3`,`col4`,`col5`,`col6` )
VALUES ( 'data20', 'data21', 'data30', 'data31', 'data40', 'data41' )
Additional note and tips:
Considering that you said you are reading data from excel sheet... Never trust input data without some tests/checks/validation. Not just because of security but stability and in general you don't want things breaking.
Those excel tables could be manually made which automatically means its prone for human error, so you can't be always 100% sure what are you gonna get.
Consider using PDO and prepared statements (security reasons, but also good practice)
I working in a php application where I must delete the selected items from a list where each item haves their own ID from mysql database, everything goes ok until execute the query in php.
This is the error message:
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 '' at line 5
this is the String that I execute in the query:
$queryDE = "delete from md5_agenda
where id_empresa = $empi
and id_unidade = $unii
and id_usuario = $usrr
and id_item_agenda in ($deletar);"
The variable $deletar receives their value from post method and their value is like: 35,36,47,... and can be one ore many different values
But my problem is if I change $deletar for the exactly values everything goes fine, but if I use the php variable with THE EXACTLY SAME VALUE it doesn't work and returns the previous error message, I have no more ideas about what to do... I wanna keep in this way where I can choose all IDs that I want delete, without repeat the query.
Thanks.
edit:
foreach($deletar as $val)
{
$queryDE = "delete from md5_agenda
where id_empresa = $empi
and id_unidade = $unii
and id_usuario = $usrr
and id_item_agenda = $val;"
}
your code is not working because $deleter is return multiple value.
check code it's working.
Why don't you use a safe parametrized query?
$db =new PDO('... your connection string ... ');
$stmt = $db->prepare("delete from md5_agenda
where id_empresa = :empi
and id_unidade = :unii
and id_usuario = :usrr
and id_item_agenda in (:deletar);");
$stmt->execute(array(
':empi' => $empi,
':unii' => $unii,
':usrr' => $usrr,
':deletar' => $deletar
)
);
Here is my code
<?php
$con = mysql_connect('localhost','test','test');
mysql_select_db('test',$con);
require_once("xml2json.php");
$testXmlFile = 'mytest.xml';
$xmlStringContents = file_get_contents($testXmlFile);
$jsonContents = "";
$jsonContents = xml2json::transformXmlStringToJson($xmlStringContents);
$obj =json_decode($jsonContents);
$rows = array();
foreach($obj->rss->channel->item as $item) {
echo $item->title."\n";
echo $item->description."\n";
$rows[] = "('".mysql_real_escape_string($item->title)."','".mysql_real_escape_string($item->description)."')";
}
$del_horoscope = "delete from jos_horoscope";
mysql_query($del_horoscope);
$query = mysql_real_escape_string("INSERT INTO `jos_horoscope` (`title`,`description`) VALUES ".implode(', ',$rows));
mysql_query($query);
if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();
?>
I am not able to insert the title and description in DB. It always says
Oh no! Something went wrong with the query: 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 '\'What\'s special today for you\',\'Your birth on the 25th day of the month (7 e' at line 1
Some of the Data which I am trying to insert is
What's special today for you
Your birth on the 25th day of the month (7 energy) modifies
your life path by giving you some special interest in technical,
scientific, or other complex and often hard to understand subjects.
You may become something of a perfectionist and a stickler for
details. Your thinking is logical and intuitive, rational and responsible.
Your feelings may run deep, but you are not very likely to let them
show. This birthday makes you a more private person, more
introspective and perhaps more inflexible.
Aries Horoscope for Thursday, April 25, 2013
Although most of us when we make a decision we don`t have to worry what it will impact for the world we live in, but when you make a decision we have to remember that it does impact our society in so many ways. Our choice has to be an ethical one, regardless of the outcome. Your emotions are brought into more conscious focus these few days. You may find that you can more easily communicate your feelings at this time.
The First line is title and rest is Description till Aries Horoscope . After that another title starts . Please help me . I tried many options but its not working for me
Here is my table structure
Please help me .
You are escaping your query multiple times, here is the correct way:
foreach($obj->rss->channel->item as $item) {
$rows[] = "('".mysql_real_escape_string($item->title)."','".mysql_real_escape_string($item->description)."')";
}
Now you don't need to escape it again:
$query = "INSERT INTO `jos_horoscope` (`title`,`description`) VALUES ".implode(', ',$rows);
mysql_query($query);
First of all, you don't want to escape the actual INSERT string. Just the values you are going to INSERT.
$query = mysql_real_escape_string("INSERT INTO `jos_horoscope` (`title`,`description`) VALUES ".implode(', ',$rows));
Is what you are currently doing. Just escape each of the values you are going to insert. Which leads us to the next problem. Your $rows[] array you are building inside the foreach loop isn't formatted properly if the foreach runs multiple times. Your insert should be inside of the foreach. And just scrap the array.
foreach($obj->rss->channel->item as $item) {
echo $item->title."\n";
echo $item->description."\n";
$title = mysql_real_escape_string($item->title);
$description = mysql_real_escape_string($item->description);
$query = "INSERT INTO `jos_horoscope` (`title`,`description`) VALUES ('$title', '$description')";
mysql_query($query);
}
Then I'm not really sure what the delete query is for.