Hi There I'm trying to get some data with this SELECT statement and when I just select two items it gives me result but when I place third item it doesn't give any result.
$Query="SELECT * from tableName WHERE status='true' AND gid='".$gid."' AND section='".$cid."'";
Plz any solution.
this one works fine, but when I add third item status='true'. doesn't work.
$Query="SELECT * from tableName WHERE gid='".$gid."' AND section='".$cid."'";
First, let me say this: Double-quoted strings can parse your variables, so this line can work, too:
$Query="SELECT * from tableName WHERE gid='$gid' AND SECTION='$cid'";
Try to learn PHP basics about using single ' and double " quotes here: What is the difference between single-quoted and double-quoted strings in PHP?
Related to the database query, is status field is present in your database table? If not, it should NOT be included within the database, or it will return FALSE boolean value. Instead, use IF if you want to be 'selectively' filtering the status of the table.
if('your conditions here'){
$query = "SELECT * FROM tableName WHERE gid='$gid' AND section='$cid'";
}
I think your mistake is the status='true'
probable the database control its field with 1 or 0 value.
Related
I have two tables, Requests & Accounting_Fundscenter_Request
I'm creating a SQL query in PHP that updates
Request_ID from Accounting_Fundscenter_Request WHERE ID is max
to
the max Request_ID from Requests
So far I have gotten the max(Request_ID) rom Requests, but I don't know how to take that value in php & sql and update the other Request_ID to equal that value.
Also, I cannot use the syntax "max(id)" because the "max" function will not work in my first query and I don't know why.
Here's what I have so far:
/* GET MAX ID FROM REQUESTS */
$selectMaxID = 'SELECT Request_ID FROM Requests ORDER BY Request_ID DESC LIMIT 1';
$maxIdResult = mysqli_query($conn, $selectMaxID); //run query
if (mysqli_num_rows($maxIdResult) > 0) {
while($maxid = mysqli_fetch_assoc($maxIdResult)) {
echo "Max Request ID: " . $maxid["Request_ID"]. "<br>";
} //echo result of
}
$insertFundsCenterMaxId = "INSERT INTO `Accounting_Fundscenter_Request` (
`Request_ID`,
VALUES (
$maxid["Request_ID"],
)
WHERE MAX(`ID`);";
/* RUN THE QUERY */
$insertFundsCenterMaxId = mysqli_query($conn, $insertFundsCenterMaxId);
This does not work. Is there a way to fix this or maybe do it in one query?
EDIT: with your help I found the solution:
You have many options here:
You can fix the syntax error you have in you insert query execution like this:
$insertFundsCenterMaxIdQuery = sprintf('INSERT INTO Accounting_Fundscenter_Request (Request_ID) VALUES (%d)', $maxid["Request_ID"]);
/* RUN THE QUERY */
$insertFundsCenterMaxId = mysqli_query($conn, $insertFundsCenterMaxIdQuery);
This way you use string formatting to replace the variable instead of directly using $maxid["Request_ID"] in a string.
Please replace %d with %s in case the Request_ID is supposed to be string/varchar.
Or you can follow another approach and just use one query to do the work like this:
INSERT INTO Accounting_Fundscenter_Request (Request_ID)
SELECT MAX(Request_ID) FROM Requests
And just execute this query
You're facing a syntax error in the update query:
$insertFundsCenterMaxId = "INSERT INTO `Accounting_Fundscenter_Request` (
`Request_ID`,
VALUES (
$maxid["Request_ID"],
)
WHERE MAX(`ID`);";
Using the double quotes in that variable hiding in the VALUES part, you are ending the string contained in insertFundsCenterMaxId. Following it is a raw string containing Request_ID which cannot be parsed by PHP. That's simply invalid code.
To solve it, you could start using prepared statements. They will also help you to secure your application against SQL injection.
There is also a solution to the syntax error problem alone - but that will leave your application vulnerable. That's why I haven't included a fix for that, but by checking how to build strings you might find it on your own. But please, please do not use it for this problem. Please.
I'm trying to include a list of strings to be used in an "in" expression in a sql statement for example:
select * from poop where id in ('asd','sas','ser')
I want to pass the in parameter from a variable. The quoting is really screwing me up. Should I be passing this as a string which I have been trying to no avail by making a comma seperated string that looks like this:
282366381A,240506808A,244154247A,491404349A,242443808B,328409296A,239723812A,383423679M
or "282366381A","240506808A","244154247A","491404349A","242443808B","328409296A"
or
'282366381A','240506808A','244154247A','491404349A','242443808B','328409296A'
None of these work or is there a different way using an array of values?
This is the statement I'm using with the string:
$cernerResults = $this->cernerdb->exec( "select
pat as HICN,
from pat
where
HICN in ( ? )", $hicsString );
Edit:
I was able to get around this by constructing the entire query as a string like this:
$query = "select pat as HICN from pat where HICN in (".$hicsString.")";
$hicsString has single quotes around each item like so:
'282366381A','240506808A','244154247A','491404349A','242443808B','328409296A'
The problem is that providing the string to the exec would result in no results. When looking at the freetds log file the in expression values would be double quoted as a whole or each one would be double single quoted and if i used no quotes they would not be quoted at all.
All of these would make the statement return no results. I should also mention that this is a Sybase database.
I think your problem may come from the fact that PDO parser needs to have one value per question mark so it is able to validate it. So your "hack" with one question mark which is assigned to more than one value is where it fails IMHO.
This is how I handle case like that:
$values = ['asd','sas','ser'];
$count = count($values);
$results = $db->exec(
"select * from poop where id in ( ?".str_repeat(", ?", $count-1).")",
$values
);
In general I would advice you using data mappers instead of running the queries on a DB object. It is easier to iterate through them and it is more secure.
I don't know PHP at all, so I am struggling through this. I need to add an or section to a MySQL query, but the values I'm searching have double quotes. I need to figure out how to add them in PHP so they are passed in to MySQL. The current query looks like:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules REGEXP "i:'.$secondlastdigit.';" and status = 1 ORDER BY id DESC LIMIT 1';
But I need to add an or statement to search for string values that looks like:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules REGEXP "i:'.$secondlastdigit.';" or skurules REGEXP "s:1:'.$secondlastdigit.';" and status = 1 ORDER BY id DESC LIMIT 1';
with double quotes surrounding the second instance of '.$secondlastdigit.'; when passed into MySQL.
My JSON string I'm searching looks like this:
a:12:{i:1;s:2:"15";i:2;s:2:"10";i:3;s:2:"30";i:4;s:2:"50";i:5;s:3:"120";i:6;s:3:"240";i:7;s:3:"480";i:8;s:3:"960";i:9;s:4:"3786";s:1:"A";s:3:"100";s:1:"C";s:2:"60";s:1:"B";s:5:"18930";}
First of all: DON'T.
If you still want to, then...REALLY DO NOT.
Making SQL queries on serialized arrays is just hell. You should try to avoid it at all costs.
Either:
Convert the serialized column into a standard SQL table
or select the column into a PHP variable, unserialize it and search through it.
Example:
$properPhpArray = unserialize($sqlResult['column_name']);
Agreed, searching serialized string is not the best solution and what the developer did despite having a bottle_size table available. I needed a quick fix and no time/skill to rewrite a tax calculation magento extension so I used replace in the query to solve my problem for now.
Since "s:1:X" will always be just one alpha character after the 1 and will not match anything else. I change the query to:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules REGEXP "i:'.$secondlastdigit.';" or replace(skurules,char(34),0) REGEXP "s:1:0'.$secondlastdigit.'0;" and status = 1 ORDER BY id DESC LIMIT 1';
Very hackish fix but gets me out of a bind for now..
Mark
The following SQL-Query is not working and results in an error. How it should be modified to work as expected?
mysql_query("SELECT * from
(SELECT * from dist WHERE Date='$_POST[date]' and Time='$_POST[time]'
group by Part, Subject, Room)
WHERE Room='$ss2a[Room]'
");
There were a few issues in the sql - most notably the use of array variables within the statement - these were not being accessed correctly within a quoted string. Also, the final where clause appeared to have a constant though I suspect that should have been a string - on closer inspection, all $_POST[var] instances failed to use quoted names ~ should be $_POST[$var] or $_POST['var']
To access array variables within a quoted string ( or certain other types of data also ) encapsulate within curly braces.
Also, field names such as Date and Time are not really valid - so you should encapsulate those in backticks.
mysql_query("select * from (
select * from dist where `Date`='{$_POST['date']}' and `Time`='{$_POST['time']}' group by `Part`, `Subject`, `Room`
) tbl where `Room`='{$ss2a['Room']}';");
Though I'm not sure I can see a reason why you need the nested select statement
I've been trying to use a PHP integer array for a MySQL query that uses the NOT IN clause, but despite no errors it seems to always return the results I want filtered out.
Example:
$IDS = $_SESSION['Posts'];
$Select = 'SELECT *
FROM status
WHERE (W_ID = '.$ID.')
AND (ID NOT IN ("'.implode(',', $IDS).'"))
ORDER BY ID DESC
LIMIT '.$Begin.', '.$Number.'';
$Select = mysql_query($Select) OR DIE(mysql_error());
I'm pretty sure this is a logical syntax error.
What I've tested for:
I've made sure that $IDS is treated as an array. Also I have tested to see whether there are values stored within the array. I have also not quoted the integer array, but then I got a mysql syntax error for not having them.
The problem is the two ” in the beginning and the end of the IN block. They cause the entire implode array to become a comma-separated string.
Your actual query will look like this:
ID NOT IN ("1,2,3,4")
"1,2,3,4" is one string, not several values. Get rid of the " quotes.
You could try to use FIND_IN_SET rather than an IN clause.
$IDS = mysql_real_escape_string(implode(',', $IDS));
$Select = "SELECT * FROM status WHERE (W_ID=$ID)
AND (NOT FIND_IN_SET(ID, '$IDS'))
ORDER BY ID DESC LIMIT $Begin, $Number";
Anyway in SQL you are required to use single quotes for strings, not double quotes. That works with MySQL, but not for all configurations. Also gets more readable if you do it the other way round. (Single quotes in PHP for performance is retarded advise!)