i am using LIKE operator in sql but is show some error.here is my code
<?php
header('Access-Control-Allow-Origin: *');
$con=mysqli_connect("url","xxxx","password","xxxx");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$callback =$_GET['callback'];
DECLARE #alpha nchar(1)
SET #alpha = 'A'
$result= mysqli_query($con,"SELECT * FROM demo WHERE Name LIKE #alpha + '%'");
$var= array();
while($row = mysqli_fetch_assoc($result))
{
$var[]=$row;
}
echo $callback."(".json_encode($var).")";
mysqli_close($con);
?>
it works properly when i am using it without alpha i.e when i give string directly.but when i am useing with vaiable it shows an error "Unexpected token <"
I am not a PHP expert, so am not sure of the syntaxes...but you can try the following:
SET #alpha = "A"
$result= mysqli_query($con,"SELECT * FROM demo WHERE Name LIKE '" + #alpha + "%'");
i.e. use the PHP strings within double inverted commas (") and the SQL strings within single inverted commas (')
Also, changing the second line as above should result in the SQL query:
SELECT * FROM demo WHERE Name LIKE 'A%' which is what I think you want. I am not sure if using the variable name within the string will result in getting its value or embed it as it is in the query.
Related
This is sample code:
include("db_connect.php");
//
function foo($string){
$s_array = array("'", '"');
$result = str_replace($s_array, "\\", $string);
return $result;
}
//
$first_var = $_POST['first_var'];
$second_var = intval($_POST['second_var']);
//
$first_var_result = foo($first_var);
//
mysql_query("UPDATE some_table SET first_column='".$first_var_result."', second_column='".$second_var."' WHERE id='id'");
When $_POST['first_var'] equals ', foo function replaces ' with \ and mysql returns ERROR.
This is not my code. I'm simpe interested in if this code is vulnerable (SQL Injection)? Thanks.
Not this one but you are very close. If first_var_result ends with ' or ", the replacement \ will escape the apostrophe in the SQL query and second_var would be executed as code. If you would escape it with foo as well, you have SQL injection.
Need help, am trying to use Select if statement in Sql
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
When z.z_status='1' and z.z_id = '".$vid."'
else JError::raiseError(404, "Message");
";
Target Objective is: show list when z_status=1 and display J Error when z_status=0. However it's not working. This function works well
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = '".$vid."'
";
However when trying to modify using else statement it does not work.
Edit - Complete Function Code:-
$database =& JFactory::getDBO();
global $Itemid;
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = '".$vid."'
";
$database->setQuery($sql);
$rows = $database->loadObjectList();
return $rows[0];
You are confusing SQL and PHP and Joomla: The second query you wrote is the one you want to run. But the logic needs to be handled in php. Your sql engine doesn't know "else" (which is php) or JError (which is Joomla). Not to speak about the wrong use of " - as you wrote it's just a syntax error.
$db = JFactory::getDbo();
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = " . $db->quote($vid);
$db->setQuery($sql);
if ($result = $db->loadObject()) {
// the query returned something, you can use the result object
echo $result->prod_name;
} else {
if ($db->getErrorNum()) {
JError::raiseError(500, "Something went horribly wrong, the query returned the error ". $db->getErrorMsg());
} else {
echo "Your query returned no records i.e. no records satisfy the z_status=1 condition";
}
}
Finally, 404 is "not found", but it refers to the request, not the data in your application. You might want to return 500 if the query errors out, and 200 for all other requests. See here for more info on status codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Following function works. But I wanna use "statement" and "like" together. If I comment out the line with constraint1 and try with:
$constraint1 = $query->statement("SELECT * FROM pages WHERE title LIKE '" . $text . "%'");
...the query doesn't work.
I got an error:
1: PHP Catchable Fatal Error: Argument 1 passed to TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelFactory::_or() must implement interface TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface, instance of TYPO3\CMS\Extbase\Persistence\Generic\Query given, called in [...] on line 439 and defined in [...]\typo3\sysext\extbase\Classes\Persistence\Generic\Qom\QueryObjectModelFactory.php line 122
Function:
/**
* Test
*
* #param string $text
* #return Objects
*/
public function findWordsByText($text) {
$query = $this->createQuery();
$query->getQuerySettings()->setRespectStoragePage(FALSE);
$query->getQuerySettings()->setReturnRawQueryResult(TRUE);
$constraint1 = $query->like('title', $text . '%');
// $constraint1 = $query->statement("SELECT * FROM pages WHERE title LIKE '" . $text . "%'");
$constraint2 = $query->like('title', 'new');
$constraint = array($constraint1, $constraint2);
$query->matching(
$query->logicalOr($constraint)
);
$records = $query->execute();
return $records;
}
If I change follwing lines:
$query->matching(
$query->logicalOr($constraint)
);
To - logicalAnd:
$query->matching(
$query->logicalAnd($constraint)
);
...the query is empty.
I don't see your problem. You want to return all records that either contain the term $text in the title field or have 'new' in the title field. So just use a simple logicalOr query:
/**
* Test
*
* #param string $text
* #return Objects
*/
public function findWordsByText($text) {
$query = $this->createQuery();
$query->getQuerySettings()->setRespectStoragePage(FALSE);
$query->getQuerySettings()->setReturnRawQueryResult(TRUE);
$query->matching(
$query->logicalOr(
$query->like('title', '%' . $text . '%'),
$query->like('title', 'new')
)
);
return $query->execute();
}
$query->statement() is for raw SQL queries and cannot be combined with createQuery.
By the way, if $text comes from a POST or GET input, don't forget to sanitize the input.
I want to perform the following query using Dapper, which currently doesn't return expected results (I think it must be treating the #pName param as literal text within the single quotes?):
var q = "SELECT * FROM Users WHERE Name LIKE '#pName%'";
#pName is the param I assign a value to upon executing the query.
Things work if I just build the SQL like:
var q = "SELECT * FROM Users WHERE Name LIKE '" + name + "%'";
.. but I would prefer to use a param if possible.
I am executing the query using the following code:
o = _cn.Query<User>(q, new { pName = new DbString { Value = name, IsFixedLength = false, Length = 25, IsAnsi = true } }).ToList();
How do I got about this using Dapper?
SELECT * FROM Users WHERE Name LIKE #pName + '%'
I would like to add here another possible solution:
var results = cn.Query("SELECT * FROM Table WHERE Column LIKE #value", new { value = value + "%" });
The wildcard is inside the string var itself, and then we reference that var in the SQL. Applies to any wildcard pattern you want.
I want to optimize some of the SQL and just need an opinion on whether I should do it or leave it as is and why I should do it. SQL queries are executed via PHP & Java, I will show an example in PHP which will give an idea of what Im doing.
Main concerns are:
-Maintainability.
-Ease of altering tables without messing with all the legacy code
-Speed of SQL (is it a concern???)
-Readability
Example of what I have right now:
I take a LONG array from a customer (cant make it smaller unfortunately) and update the existing values with the new values provided by a customer in the following way:
$i = 0;
foreach($values as $value)
{
$sql = "UPDATE $someTable SET someItem$i = '$value' WHERE username='$username'";
mysql_query($sql, $con);
$i+=1;
}
Its easy to see from the above example that if the array of values is long, than I execute a lot of SQL statements.
Should I instead do something like:
$i = 0;
$j = count($values);
$sql = "UPDATE $someTable SET ";
foreach($values as $value)
{
if($i < $j) //append values to the sql string up to the last item
{
$sql .= "someItem$i = '$value', ";
}
$i+=1;
}
$sql .= "someItem$i = '$value' WHERE username='$username'"; //add the last item and finish the statement
mysql_query($sql, $con); //execute query once
OR which way should it be done / should I bother making these changes? (there a lot of the type and they all have 100+ items)
Thanks in advance.
The only way you'll get a definitive answer is to run both of these methods and profile it to see how long they take. With that said, I'm confident that running one UPDATE statement with a hundred name value pairs will be faster than running 100 UPDATE statements.
Don't run 100 seperate UPDATE statements!
Use a MySQL wrapper class which, when given an array of name => value pairs will return an SQL UPDATE statement. Its really simple. I'm just looking for the one we use now...
We use something like this (registration required) but adapted a little more to suit our needs. Really basic but very very handy.
For instance, the Update method is just this
/**
* Generate SQL Update Query
* #param string $table Target table name
* #param array $data SQL Data (ColumnName => ColumnValue)
* #param string $cond SQL Condition
* #return string
**/
function update($table,$data,$cond='')
{
$sql = "UPDATE $table SET ";
if (is_string($data)) {
$sql .= $data;
} else {
foreach ($data as $k => $v) {
$sql .= "`" . $k . "`" . " = " . SQL::quote($v) . ",";
}
$sql = SQL::trim($sql , ',');
}
if ($cond != '') $sql .= " WHERE $cond";
$sql .= ";";
return $sql;
}
If you can't change the code, make sure it is enclosed in transaction (if the storage engine is InnoDB) so no non-unique indexes will be updated before commiting transaction (this will speed up the write) and the new row won't be flushed to disk.
If this is MyISAM table, use UPDATE LOW_PRIORTY or lock table before the loop and unlock after read.
Of course, I'm sure you have index on the username column, but just to mention it - you need such index.