MySQL/PHP Boolean Fulltext Search Issue in Laravel 4 - php

I have the following code that searches my models in Laravel 4 for a search phrase. It uses 'IN BOOLEAN MODE' and MATCH() and AGAINST().
public function scopeSearch($query, $q)
{
$fields = Static::getFields();
$fields = implode(', ', $fields);
$query->whereRaw("MATCH(" . $fields . ") AGAINST('" . $q . "' IN BOOLEAN MODE)");
}
public static function getFields()
{
$field_names = array();
$disallowed = array('id', 'created_at', 'updated_at', 'deleted_at');
$columns = DB::select('SHOW COLUMNS FROM accounts');
foreach ($columns as $c) {
$field = $c->Field;
if ( ! in_array($field, $disallowed)) {
$field_names[$field] = $field;
}
}
return $field_names;
}
I'd like help modifying the code above to allow a user to search the fields using partial words and phrases. For example, if a user types purple, I'd like the search to also find any records with email addresses containing the word purple, so info#purplegriffon.com. So, essentially partial matches.
I'd also like to be able to find everything containing griffon in the field for the typed phrase john griffon, even if john does not exist.
Can anyone help me out with this? Cheers.

OK, I've got it working as best I can with FULLTEXT search and using wildcard operators to search for partials. This may not be the best solution but it works.
public function scopeSearch($query, $q)
{
$fields = Static::getFields();
$fields = implode(', ', $fields);
$terms = explode(' ', $q);
if (count($terms) > 1) {
$query->whereRaw("MATCH(" . $fields . ") AGAINST ('" . $q . "' IN BOOLEAN MODE)");
} else {
foreach ($terms as $term) {
$query->whereRaw("MATCH(" . $fields . ") AGAINST ('*" . $term . "*' IN BOOLEAN MODE)");
}
}
}
public static function getFields()
{
$field_names = array();
$disallowed = array('id', 'country_id', 'created_at', 'updated_at', 'deleted_at');
$columns = DB::select('SHOW COLUMNS FROM venues');
foreach ($columns as $c) {
$field = $c->Field;
if ( ! in_array($field, $disallowed)) {
$field_names[$field] = $field;
}
}
return $field_names;
}
If anyone can either simplify or improve this, then I would love to see it. Cheers.

i got solution by :
$terms = mysql_real_escape_string($terms);
$contact_results = Contact::where_account_user_id(Auth::user()->account_user_id)
->raw_where("match (`first`, `last`) against ('{$terms}*' IN BOOLEAN MODE)")
->where_deleted(0)
->paginate(20);
phpconsole($contact_results->results);
return $contact_results;

Related

Laravel | Unable to get the search results filtered for *multiple keywords* | Returns all from the table now

Code(Controller):
public function index(Request $request) {
try {
$this->productRepository->pushCriteria(new RequestCriteria($request));
$this->productRepository->pushCriteria(new LimitOffsetCriteria($request));
$this->productRepository->pushCriteria(new ProductsOfFieldsCriteria($request));
if ($request->get('trending', null) == 'week') {
$this->productRepository->pushCriteria(new TrendingWeekCriteria($request));
} else {
$this->productRepository->pushCriteria(new NearCriteria($request));
}
$queryString = $request->query;
if ($queryString = $request->query('search')) {
// [$column, $term] = explode(':', $queryString);
$terms = explode(" ", request('q'));
$products = Product::query()->whereHas('store', function ($query) use ($terms) {
foreach ($terms as $term) {
// Loop over the terms and do a search for each.
$query->where('name', 'like', '%' . $term . '%');
}
})->get();
} else {
$products = $this->productRepository->all();
}
}
catch(RepositoryException $e) {
return $this->sendError($e->getMessage());
}
return $this->sendResponse($products->toArray(), 'Products retrieved successfully');
}
I'm getting the complete set of data within the product table as of now. My intension is to be able to filter the results with matching keywords as in $terms . Can someone please help figure out what's missing in filtering above ?
Didn't get much help around & solved this myself. To the ones who may need this in future:
$condition = '';
$terms = explode(" ",$queryString);
foreach($terms as $text)
{
$condition .= "name LIKE '%".($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$sql_query = "SELECT * FROM products WHERE " . $condition;
$result = DB::select($sql_query);
condition is going to gather all the conditions to be searched.
terms is going to collect all searches from the URL text is the
invidual items from the array.
products is the name of the table.
use DB; should be initialized if you're in a different namespace.

PDO Function simplification

Here is my function.
I want to simplify this function.
Any one help me please?
public function showData($table,$fields,$values)
{
$first = true;
$whereClause=null;
foreach($fields as $key => $value)
{
if($first)
{
$whereClause .= " WHERE $value = '$values[$key]'";
$first = false;
}
else
{
$whereClause .= " AND $value = '$values[$key]'";
}
}
$sql = "SELECT * FROM $table $whereClause";
$q = $this->conn->prepare($sql) or die("failed!");
$q->execute();
while ($r = $q->fetch(PDO::FETCH_ASSOC))
{
$data[] = $r;
}
return $data;
}
foreach($ob->showData($tablenm,$field,$val) as $roleval)
{
//Do Something
}
Any other way to simplify this function.
Help me please.
public function query($sql, $params = NULL)
{
$stmt = $this->conn->prepare($sql);
$stmt->execute($params)
return $stmt;
}
$data = $ob->query("SELECT * FROM table WHERE foo = ? AND bar = ?", [$foo, $bar]);
foreach($data as $roleval)
{
//Do Something
}
This function is way more simpler, way more powerful and way more flexible than yours. Put aside that yours is essentially and irrecoverably prone to SQL injection, just mocking a prepared statement but not using it really.
You have to understand that keywords in SQL serve for the great purpose of readability, makes whole statement readable and unambiguous, comprehensible by the every programmer in the world. And so you can tell that your initial idea to save yourself typing of SELECT or WHERE turns to be not that brilliant.
Besides, PDO supports dozens of different return formats, while you are limiting yourself with only one.
You may read further in my article Your first database wrapper's childhood diseases
function showData($table, $fields, $values) {
if(!(is_array($fields) && is_array($values) ) || count($fields) !== count($values))
throw new Exception('Arguments error: "fields" and "values" must be arrays with equal number of elements.');
foreach ($fields as $key => &$field)
$field = '`' . str_replace('`', '``', $field) . '` = ' . $this->conn->quote($values[$key]);
return 'SELECT * FROM `' . str_replace('`', '``', $table) . (empty($fields) ? '`' : '` WHERE ' . implode(' AND ', $fields)) . ';';
}
test case:
echo showData('table`name', ['col`1', 'col\`2', 'col\\`3'], ["Tom's cat 1", "Tom's cat 2", "Tom's cat 3"]);
#output: SELECT * FROM `table``name` WHERE `col``1` = 'Tom\'s cat 1' AND `col\``2` = 'Tom\'s cat 2' AND `col\``3` = 'Tom\'s cat 3';
Of course you will execute the SQL instead of returning it as test output.

Concatenation of string with a specific array elements

the given code below insert data from an array to the mysql table.as its not the full code but what i want to know is available in this code. my question is that there is a field in table named "image_url" but the data in that field only have image name and i want to append http://www.xxxxxx.com at the start of every image name and the replace it with the image name in the field but i dont know how to do that plz help me out
thanks in advance
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (".implode(',',array_keys($v)).") VALUES ('".implode("','",$v)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}
This snippet should do what you want:
if (isset($v['image_url'])) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
}
You can concatenate strings with the dot "."!
At first... Is your application protected against SQL injection? If not you should build two methods/functions like this using mysql_real_escape_string():
function sqlSafeKey( $key){
return '`' . mysql_real_escape_string( $key) . `'`;
}
function sqlSafeValue( $value){
return "'" . mysql_real_escape_string( $value) . "'";
}
And than use array_map() to escape your values like this:
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
About your question... The matzino's answer is correct and whole loop should look like this:
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
$query = "INSERT INTO test (".implode(',', $keys).
") VALUES ('".implode("','",$values)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}

Is there a lightweight sql parser class written in PHP to do this? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Before jumping in and rolling my own, I thought I'd ask in here first.
I am looking to do some elementary parsing of random SQL commands in order to:
inspect the field names that are being used in 'SELECT's (including any subqueries)
inspect the field names that are being used in 'JOIN's (including any subqueries)
inspect the names of tables being used in the query (including any subqueries)
I have seen some SQL parser classes out there, but they are far too 'heavyweight' for the use cases described above.
Is anyone aware of a lightweight class that has atleast some of the required functionality?
Worst case scenario, if I have to write a parser, what would be the best way of writing such a parser (normally, to write a parser, I would normally resort to tools that are not available in PHP), any tips on how to write a 'rough and ready' class to do this parsing?
//rough sketch
<?php
class SqlParser()
{
protected $sqlstr;
protected $m_tablenames = array();
protected $m_fieldnames = array();
public function __construct($sql){
$this->sqlstr = $sqlcmd;
$this->parseString($sqlstr);
}
public function __destroy(){}
public function getTableNames(){ return m_tablenames; }
public function getFieldNames(){ return m_fieldnames; }
private function parseString($sql)
{
//TODO
}
}
?>
I would prefer the parsing to be SQL dialect agnostic (i.e. not tied to any particular SQL dialect or db specific SQL) as much as possible.
If that is not possible, then the SQL dialect I will be using is PostgreSQL.
PHP SQL Parser might be what you're looking for. It'll handle fairly complex queries, as you can see from the link. Download the code from the projects front page. The only drawback is it targets MySQL only. Adding support for PostgreSQL should be no big problem.
There's also a more basic solution for SQL parsing: PHP SQL Tokenizer, but it does not offer you anything but select/from/where/order separation: no field names, subquery extraction, or such.
You might give cbMySQL a try, i do not know it very well, but it might be the thing you are looking for.
I tried do this recently
PHP-Light-SQL-Parser-Class this is more light that the other classes
<?php
/**
* Light SQL Parser Class
* #author Marco Cesarato <cesarato.developer#gmail.com>
* #copyright Copyright (c) 2018
* #license http://opensource.org/licenses/gpl-3.0.html GNU Public License
* #link https://github.com/marcocesarato/PHP-Light-SQL-Parser-Class
* #version 0.1.86
*/
class LightSQLParser {
// Public
public $query = '';
// Private
protected static $connectors = array('OR', 'AND', 'ON', 'LIMIT', 'WHERE', 'JOIN', 'GROUP', 'ORDER', 'OPTION', 'LEFT', 'INNER', 'RIGHT', 'OUTER', 'SET', 'HAVING', 'VALUES', 'SELECT', '\(', '\)');
protected static $connectors_imploded = '';
/**
* Constructor
*/
public function __construct($query = '') {
$this->query = $query;
if(empty(self::$connectors_imploded))
self::$connectors_imploded = implode('|', self::$connectors);
return $this;
}
/**
* Set SQL Query string
*/
public function setQuery($query) {
$this->query = $query;
return $this;
}
/**
* Get SQL Query method
* #param $query
* #return string
*/
public function method($query = null){
$methods = array('SELECT','INSERT','UPDATE','DELETE','RENAME','SHOW','SET','DROP','CREATE INDEX','CREATE TABLE','EXPLAIN','DESCRIBE','TRUNCATE','ALTER');
$queries = empty($query) ? $this->_queries() : array($query);
foreach($queries as $query){
foreach($methods as $method) {
$_method = str_replace(' ', '[\s]+', $method);
if(preg_match('#^[\s]*'.$_method.'[\s]+#i', $query)){
return $method;
}
}
}
return '';
}
/**
* Get Query fields (at the moment only SELECT/INSERT/UPDATE)
* #param $query
* #return array
*/
public function fields(){
$fields = array();
$queries = $this->_queries();
foreach($queries as $query) {
$method = $this->method($query);
switch ($method){
case 'SELECT':
preg_match('#SELECT[\s]+([\S\s]*)[\s]+FROM#i', $query, $matches);
if (!empty($matches[1])) {
$match = trim($matches[1]);
$match = explode(',', $match);
foreach ($match as $field) {
$field = preg_replace('#([\s]+(AS[\s]+)?[\w\.]+)#i', '', trim($field));
$fields[] = $field;
}
}
break;
case 'INSERT':
preg_match('#INSERT[\s]+INTO[\s]+([\w\.]+([\s]+(AS[\s]+)?[\w\.]+)?[\s]*)\(([\S\s]*)\)[\s]+VALUES#i', $query, $matches);
if (!empty($matches[4])) {
$match = trim($matches[4]);
$match = explode(',', $match);
foreach ($match as $field) {
$field = preg_replace('#([\s]+(AS[\s]+)?[\w\.]+)#i', '', trim($field));
$fields[] = $field;
}
} else {
preg_match('#INSERT[\s]+INTO[\s]+([\w\.]+([\s]+(AS[\s]+)?[\w\.]+)?[\s]*)SET([\S\s]*)([\;])?#i', $query, $matches);
if (!empty($matches[4])) {
$match = trim($matches[4]);
$match = explode(',', $match);
foreach ($match as $field) {
$field = preg_replace('#([\s]*\=[\s]*[\S\s]+)#i', '', trim($field));
$fields[] = $field;
}
}
}
break;
case 'UPDATE':
preg_match('#UPDATE[\s]+([\w\.]+([\s]+(AS[\s]+)?[\w\.]+)?[\s]*)SET([\S\s]*)([\s]+WHERE|[\;])?#i', $query, $matches);
if (!empty($matches[4])) {
$match = trim($matches[4]);
$match = explode(',', $match);
foreach ($match as $field) {
$field = preg_replace('#([\s]*\=[\s]*[\S\s]+)#i', '', trim($field));
$fields[] = $field;
}
}
break;
case 'CREATE TABLE':
preg_match('#CREATE[\s]+TABLE[\s]+\w+[\s]+\(([\S\s]*)\)#i', $query, $matches);
if (!empty($matches[1])) {
$match = trim($matches[1]);
$match = explode(',', $match);
foreach ($match as $_field) {
preg_match('#^w+#', trim($_field), $field);
if (!empty($field[0])) {
$fields[] = $field[0];
}
}
}
break;
}
}
return array_unique($fields);
}
/**
* Get SQL Query First Table
* #param $query
* #return string
*/
public function table(){
$tables = $this->tables();
return $tables[0];
}
/**
* Get SQL Query Tables
* #return array
*/
function tables(){
$results = array();
$queries = $this->_queries();
foreach($queries as $query) {
$patterns = array(
'#[\s]+FROM[\s]+(([\s]*(?!'.self::$connectors_imploded.')[\w]+([\s]+(AS[\s]+)?(?!'.self::$connectors_imploded.')[\w]+)?[\s]*[,]?)+)#i',
'#[\s]*INSERT[\s]+INTO[\s]+([\w]+)#i',
'#[\s]*UPDATE[\s]+([\w]+)#i',
'#[\s]+[\s]+JOIN[\s]+([\w]+)#i',
'#[\s]+TABLE[\s]+([\w]+)#i'
);
foreach($patterns as $pattern){
preg_match_all($pattern,$query, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
$tables = explode(',', $val[1]);
foreach ($tables as $table) {
$table = trim(preg_replace('#[\s]+(AS[\s]+)[\w\.]+#i', '', $table));
$results[] = $table;
}
}
}
}
return array_unique($results);
}
/**
* Get all queries
* #return array
*/
protected function _queries(){
$queries = preg_replace('#\/\*[\s\S]*?\*\/#','', $this->query);
$queries = preg_replace('#;(?:(?<=["\'];)|(?=["\']))#', '', $queries);
$queries = preg_replace('#[\s]*UNION([\s]+ALL)?[\s]*#', ';', $queries);
$queries = explode(';', $queries);
return $queries;
}
}
EXAMPLE USAGE
header("Content-Type: text/plain");
echo '========= Light SQL Parser DEMO =========' . PHP_EOL;
echo PHP_EOL . '### UPDATE ###' . PHP_EOL;
$lsp = new LightSQLParser("UPDATE Customers as ae
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;");
// OR
/*
$lsp = new LightSQLParser();
$lsp->setQuery("UPDATE Customers as ae
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;");
*/
echo PHP_EOL . 'METHOD' . PHP_EOL;
var_dump($lsp->method());
echo PHP_EOL . 'TABLES' . PHP_EOL;
var_dump($lsp->tables());
echo PHP_EOL . 'FIELDS' . PHP_EOL;
var_dump($lsp->fields());
echo PHP_EOL . '### SELECT ###' . PHP_EOL;
$lsp->setQuery("SELECT surname, given_names, title FROM Person
JOIN Author on person.ID = Author.personID
JOIN Book on Book.ID = Author.publicationID
UNION ALL
SELECT surname, given_names, title FROM Person
JOIN Author on person.ID = Author.personID
JOIN Article on Article.ID = Author.publicationID");
echo PHP_EOL . 'METHOD' . PHP_EOL;
var_dump($lsp->method());
echo PHP_EOL . 'TABLES' . PHP_EOL;
var_dump($lsp->tables());
echo PHP_EOL . 'FIELDS' . PHP_EOL;
var_dump($lsp->fields());
echo PHP_EOL . '### INSERT ###' . PHP_EOL;
$lsp->setQuery("INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');");
echo PHP_EOL . 'METHOD' . PHP_EOL;
var_dump($lsp->method());
echo PHP_EOL . 'TABLES' . PHP_EOL;
var_dump($lsp->tables());
echo PHP_EOL . 'FIELDS' . PHP_EOL;
var_dump($lsp->fields());

PHP Implode Associative Array

So I'm trying to create a function that generates a SQL query string based on a multi dimensional array.
Example:
function createQueryString($arrayToSelect, $table, $conditionalArray) {
$queryStr = "SELECT ".implode(", ", $arrayToSelect)." FROM ".$table." WHERE ";
$queryStr = $queryStr.implode(" AND ",$conditionalArray); /*NEED HELP HERE*/
return $queryStr;
}
$columnsToSelect = array('ID','username');
$table = 'table';
$conditions = array('lastname'=>'doe','zipcode'=>'12345');
echo createQueryString($columnsToSelect, $table, $conditions); /*will result in incorrect SQL syntax*/
as you can see I need help with the 3rd line as it's currently printing
SELECT ID, username FROM table WHERE
lastname AND zipcode
but it should be printing
SELECT ID, username FROM table WHERE
lastname = 'doe' AND zipcode = '12345'
You're not actually imploding a multidimensional array. $conditions is an associative array.
Just use a foreach loop inside your function createQueryString(). Something like this should work, note it's untested.:
$terms = count($conditionalArray);
foreach ($conditionalArray as $field => $value)
{
$terms--;
$queryStr .= $field . ' = ' . $value;
if ($terms)
{
$queryStr .= ' AND ';
}
}
Note: To prevent SQL injection, the values should be escaped and/or quoted as appropriate/necessary for the DB employed. Don't just copy and paste; think!
function implodeItem(&$item, $key) // Note the &$item
{
$item = $key . "=" . $item;
}
[...]
$conditionals = array(
"foo" => "bar"
);
array_walk($conditionals, "implodeItem");
implode(' AND ', $conditionals);
Untested, but something like this should work. This way you can also check if $item is an array and use IN for those cases.
You will have to write another function to process the $conditionalArray, i.e. processing the $key => $value and handling the types, e.g. applying quotes if they're string.
Are you just dealing with = condition? What about LIKE, <, >?
Forgive me if its not too sexy !
$data = array('name'=>'xzy',
'zip'=>'3432',
'city'=>'NYK',
'state'=>'Alaska');
$x=preg_replace('/^(.*)$/e', ' "$1=\'". $data["$1"]."\'" ',array_flip($data));
$x=implode(' AND ' , $x);
So the output will be sth like :
name='xzy' AND zip='3432' AND city='NYK' AND state='Alaska'
I'd advise against automated conditionals creation.
Your case is too local, while there can be many other operators - LIKE, IN, BETWEEN, <, > etc.
Some logic including several ANDs and ORs.
The best way is manual way.
I am always doing such things this way
if (!empty($_GET['rooms'])) $w[]="rooms='".mesc($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mesc($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mesc($_GET['max_price'])."'";
Though if you still want it with this simple array, just iterate it using
foreach ($conditions as $fieldname => $value)...
and then combine these variables in the way you need. you have 2 options: make another array of this with field='value' pairs and then implode it, or just concatenate, and substr trailing AND at the end.
I use a variation of this:
function implode_assoc($glue,$sep,$arr)
{
if (empty($glue)) {$glue='; ';}
if (empty($sep)) {$sep=' = ';}
if (is_array($arr))
{
foreach ($arr as $k=>$v)
{
$str .= $k.$sep.$v.$glue;
}
return $str;
} else {
return false;
}
};
It's rough but works.
Here is a working version:
//use: implode_assoc($v,"="," / ")
//changed: argument order, when passing to function, and in function
//output: $_FILES array ... name=order_btn.jpg / type=image/jpeg / tmp_name=G:\wamp\tmp\phpBDC9.tmp / error=0 / size=0 /
function implode_assoc($arr,$glue,$sep){
$str = '';
if (empty($glue)) {$glue='; ';}
if (empty($sep)) {$sep=' = ';}
if (is_array($arr))
{
foreach ($arr as $key=>$value)
{
$str .= $key.$glue.$value.$sep;
}
return $str;
} else {
return false;
}
}
I know this is for the case of a pdo mysql type.. but what i do is build pdo wrapper methods, and in this case i do this function that helps to build the string, since we work with keys, there is no possible way to mysql inject, since i know the keys i define / accept manually.
imagine this data:
$data=array(
"name"=>$_GET["name"],
"email"=>$_GET["email"]
);
you defined utils methods...
public static function serialize_type($obj,$mode){
$d2="";
if($mode=="insert"){
$d2.=" (".implode(",",array_keys($obj)).") ";
$d2.=" VALUES(";
foreach ($obj as $key=>$item){$d2.=":".$key.",";}
$d2=rtrim($d2,",").")";}
if($mode=="update"){
foreach ($obj as $key=>$item){$d2.=$key."=:".$key.",";}
}
return rtrim($d2,",");
}
then the query bind array builder ( i could use direct array reference but lets simplify):
public static function bind_build($array){
$query_array=$array;
foreach ($query_array as $key => $value) { $query_array[":".$key] = $query_array[$key]; unset($query_array[$key]); } //auto prepair array for PDO
return $query_array; }
then you execute...
$query ="insert into table_x ".self::serialize_type( $data, "insert" );
$me->statement = #$me->dbh->prepare( $query );
$me->result=$me->statement->execute( self::bind_build($data) );
You could also go for an update easy with...
$query ="update table_x set ".self::serialize_type( $data, "update" )." where id=:id";
$me->statement = #$me->dbh->prepare( $query );
$data["id"]="123"; //add the id
$me->result=$me->statement->execute( self::bind_build($data) );
But the most important part here is the serialize_type function
Try this
function GeraSQL($funcao, $tabela, $chave, $valor, $campos) {
$SQL = '';
if ($funcao == 'UPDATE') :
//Formata SQL UPDATE
$SQL = "UPDATE $tabela SET ";
foreach ($campos as $campo => $valor) :
$SQL .= "$campo = '$valor', ";
endforeach;
$SQL = substr($SQL, 0, -2);
$SQL .= " WHERE $chave = '$valor' ";
elseif ($funcao == 'INSERT') :
//Formata SQL INSERT
$SQL = "INSERT INTO $tabela ";
$SQL .= "(" . implode(", ", array_keys($campos) ) . ")";
$SQL .= " VALUES ('" . implode("', '", $campos) . "')";
endif;
return $SQL;
}
//Use
$data = array('NAME' => 'JOHN', 'EMAIL' => 'J#GMAIL.COM');
GeraSQL('INSERT', 'Customers', 'CustID', 1000, $data);

Categories