Sql like query with variable? - php

I have this function:
function word($arg){
echo ''.$arg.'';
//echoes test
require ('config.php');
$requestSQL = mysql_query("SELECT * FROM db where eng LIKE '%$arg%' order by id ASC LIMIT 10", $connection);
while ($row = mysql_fetch_array($requestSQL))
{
echo ''.$row['id'].': '.$row['eng'].'<br>';
}
}
Gets triggered by:
$number = $explode[1];
word($number);
But doesn't echo values from the database, nothing at all.
If I echo $arg (in the function), it shows the value. If I replace in my sql query: '%$arg%' with '%test%', it echoes the correct value.
Is the '%$arg%' syntax wrong?

You should use a proper concat
"SELECT * FROM db where eng LIKE concat('%', '$arg', '%') order by id ASC LIMIT 10"

It's pretty simple, all you do is: LIKE %{$arg}%. Because I am assuming that $arg is a text value. If a variable is a text value then you must do this to keep it working. You wrap text variables in {}.
Also, never . . . EVER use mysql_*, you should move to mysqli_* or PDO/OOP. It's just good practice.
Update
You can't use variables within mysql_query("", $connection) quotes. Instead, do this:
$query = "SELECT * FROM db WHERE eng LIKE '%{$arg}%' ORDER BY id ASC LIMIT 10";
// then use this variable as a replacement for the quotes in the mysql_query().
$set = mysql_query($query, $connection); // like so . . .
// mysql_fetch_assoc() is the same as mysql_fetch_array().
while($row = mysql_fetch_assoc($set)) {
echo "".$row['id'].": ".$row['eng']."<br>";
}

I'm so stupid, actually $explode[1]; was returning the correct value but had a blank line in the source code. So I had to use trim and now it works.

Related

SQLite using variable in LIKE query in PHP

All I want to do, user inputs full or partial Membership Number, and query the SQLite database.
The query will work if you use LIKE %21%, just can't use a variable.
$name=$_POST['mem_num'];
$db = new MyDB();
$result = $db->query('SELECT * FROM details WHERE MEM_NUMBER LIKE '%$name%' ');
while ($row = $result->fetchArray()) {
print $row["MEM_NUMBER"] . "\n";
}
I can do this is MySQL in seconds, but not in SQLite!
$result = $db->query("SELECT * FROM details WHERE MEM_NUMBER LIKE '%" . $name . "%'");
How about this?
To use variables in PHP string, you need to enclose it in double quotes "SELECT ... LIKE '%$name%'"
$result = $db->query('SELECT * FROM details WHERE MEM_NUMBER LIKE "%'.$name.'%" ');
You need to concatenate your query and your variable using dots and to put the percent signs as a part of the strings.

Split mysql query and delete a part of that

I have many conditions in PHP function which every of them produces a mysql query.All conditions work correctly except one query which ends with AND operator.Before returning the query result I need to check if query ends with AND it should remove AND and then returnes the query.
This is the sample of query:
$query="select * from case where case_name='name' AND case_status='102' AND";
If this kind of query is produced I need to do:
1-If it ends with AND
2-remove AND
3-return the query without last AND
The result should be like this:
$query="select * from case where case_name='name' AND case_status='102' ";
I do not have much experience to work with PHP functions.How can I do this?
Thnaks for your help.
Try this,
$query="select * from case where case_name='name' AND case_status='102' AND"
$query = trim($query,'AND');
quick fix:
$query = preg_replace( "/AND$/", "", $query);
You should fix the logic of condition though.
like
$cond[] = "....";
$cond[] = "...."
....
then
$query = $query_first_half + implode ( " AND " , $cond );
Ultimately please use sql library like PDO
http://fi1.php.net/manual/en/class.pdo.php
explode the string and pop the last element .
$arr = explode(" ", $query);
$last = array_pop($arr);
if($last != "and")
{
array_push($arr,$last);
}
$query = implode(" ",$arr);
Run the $query them it should work
First your table name CASE is mysql reserved keyword you should rename your table to something else or escpae it by backticks `
you could use query without AND , and when you add other query just start by AND .
like that :
$query="select * from `case` where case_name='name' AND case_status='102'";
$query .= " AND .........";
so like that , your condition is not true then just first query will work , if condition is true then second query will work and it start by AND. You dont need to remove the AND.

Cannot pass a string to a SQL Query

I have the following code:
$RefEquipamento = mysql_real_escape_string($_GET['ID']);
mysql_select_db($database_connLOOPGEST, $connLOOPGEST);
$query_rs_equipamento = sprintf("SELECT * FROM clientes_listaequipamentos WHERE referenciacliente = $RefEquipamento ORDER BY datacriacao_loop DESC LIMIT 1");
$rs_equipamento = mysql_query($query_rs_equipamento, $connLOOPGEST) or die(mysql_error());
$row_rs_equipamento = mysql_fetch_assoc($rs_equipamento);
$totalRows_rs_equipamento = mysql_num_rows($rs_equipamento);
echo json_encode($row_rs_equipamento);
I'm not an expert in PHP or MySQL, I'm trying to learn something. I'm using Dreamweaver.
The code above works when I pass a number as an argument (for ex. If $RefEquipamento is 200456) this works fine, but when I tried to pass a string (let's say I'm passing the string "equip1" this doesn't work, the echo gives me the following message:
"Unknown column 'equip1' in 'where clause'"
try:
$RefEquipamento = "'" . mysql_real_escape_string($_GET['ID']) . "'";
so mysql will handle it as a string.
OR
$query_rs_equipamento = sprintf("SELECT * FROM clientes_listaequipamentos WHERE referenciacliente = '$RefEquipamento' ORDER BY datacriacao_loop DESC LIMIT 1");
If you send to MySQL command a word, without marking with --> ' <---- MySQL Understand you are giving the name of a field or columns.
Remember that allways you need to past a word as variable, you need mark it.
the number don't need special mark
Yoni Hassin response is the solution, mark it as answer

Session variable is not working in MySQL statement

I am trying to use session variable($_SESSION['asc_id'], which holds some value like "AS0027001") in an SQL statement, but it is not working.
When I hardcode the value, it is providing results.
Can anyone please correct me.
MySQL query which is not working
$asc_id = $_SESSION['asc_id'];
$rs = mysql_query('select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = "$asc_id"
and lname_fname_dob like "' .
mysql_real_escape_string($_REQUEST['term']) .
'%" order by lname_fname_dob asc limit 0,10', $dblink);
Mysql query which is working
$rs = mysql_query('select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = "AS0027001" and lname_fname_dob like "' .
mysql_real_escape_string($_REQUEST['term']) .
'%" order by lname_fname_dob asc limit 0,10', $dblink);
Variable substitution only works within double quoted strings, not single quoted ones. In other words, you should do;
$rs = mysql_query("select .... and asc_id = '$asc_id' and ... limit 0,10", $dblink);
Btw, you did make sure the value doesn't include any characters that may lead to SQL injection, right? Otherwise you should use mysql_real_escape_string to make sure before inserting it into a query.
When you print the strings, it will be clear. When the question is reformatted to leave the SQL readable, the problem is clear. (The first rule for debugging SQL statements is "print the string". A second rule, that makes it easier to comply with the first, is always put the SQL statements into a string which you pass to the SQL function.)
You use the . notation to embed the request term in the string; you don't use that to embed the $asc_id into the string. You should also use mysql_real_escape_string() on the session ID value to prevent SQL injection.
First print the variable $asc_id . If it displays nothing, session is unavailable . In that case you missed session_start() in top of the current executing page .
From the SQL query, you cannot replace the value of a variable inside single quoted string .
Use . symbol for mixing string value with variable or use double quoted string . I prefer first one .
For troubleshooting , simplest method is printing variable values. From the result , you will understand what is missing .
Thanks
Try this. from the comment you added, I modified it like this
session_start(); //add this if you did not do it yet
$asc_id = $_SESSION['asc_id'];
$rs = mysql_query("select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = '$asc_id'
and lname_fname_dob like '".
mysql_real_escape_string($_REQUEST['term']) .
"%' order by lname_fname_dob asc limit 0,10", $dblink);

MySQL Delete Item from Table not working

I am trying to delete a record in my db based on the unique id ($id). Is there something wrong with this code? Probably a simple one for you php pro's.
function delAccount(){
mysql_query("DELETE FROM accounts WHERE id=".$id."LIMIT 1");
}
I get a :
Fatal error: Can't use function return value in write context in
/home/content/53/7311353/html/cca/accounts/include/processAct.php on line 15
My Class that I have powering everything:
class Accounts
{
function Accounts(){
if (isset($_POST['addacct'])){
$this->addAccount();
}elseif(isset($_POST['editacct'])){
$this->editAccount();
}elseif(isset($_POST['delacct'])){
$this->delAccount();
}else{
// redirect if loaded without a POST value set
header("Location: ../index.php?o=illegal&t=nodata");
}
}
You should, first of all, put a space between ".$id." and LIMIT so:
mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");
Secondly, the $id is NOT available within this function by default. Either do this:
function delAccount($id) {
mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");
}
and use delAccount($id_parameter); in your script to send the ID along with the function. Or try this:
function delAccount() {
global $id;
mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");
}
then you can call this function after you set the value of $id somewhere else in your code.
First: is the value for $id actually an id in the database? Second you need a space before "LIMIT", ie:
" LIMIT 1".
Are you sure $id is set?
If $id should be sent to the function as an argument, try this:
function delAccount($id) {
mysql_query("DELETE FROM accounts WHERE id=" . $id . " LIMIT 1");
}
EDIT: You missed a space character between the ID and the LIMIT.
Added some small improvements to the form of the query string:
function delAccount($id) {
mysql_query("DELETE FROM `accounts` WHERE `id` = " . $id . " LIMIT 1");
}
EDIT:
The error you get doesn't come from MySQL itself. Have you checked the returned value. It might return another error, or the returned value might be correct, but used in an erroneous way in later code.
Your error is from the PHP compiler. Are you doing something like this on line 15:
if (delAccount(...) = false) { ... }
? If so, change to ==.
Some hints on how to debug stuff like this.
If you suspect something is wrong, the first thing to do is to output the generated query. Like so:
$query = "DELETE FROM accounts WHERE id=".$id."LIMIT 1";
echo $query; // for debugging
That will show you that at least one thing is wrong with your query: You have a space missing before LIMIT.
mysql_query() returns false if it encounters an error. You can check for that, and output it using mysql_error(). Like so:
$result = mysql_query($query);
if(!$result) trigger_error("Database error!: ".mysql_error());
If $id comes from outside, like the $_GET array, make sure you have tested whether it is an integer before using it in a query to avoid SQL injection.

Categories