SQL OR not returning all rows - php

I'm having what may be the dumbest issue.
I'm using phpmyadmin and when I query a table using OR it does not return all values.
This is the query that is not returning all values:
SELECT * FROM ecrdatabase.ecrtable m WHERE m.ecrChangeOwner = '$partialOwner' OR m.ecrInitByName = '$partialOwner'.
Here, $partialOwner is passed from $_GET['user'].
Some of the rows are returned - just not all of them. I have a php page that queries the database and I have tried running the query directly on the database through phpmyadmin using query:
SELECT * FROM ecrtable WHERE ecrChangeOwner = 'ecunningham' OR ecrInitByName = 'ecunningham'.
Both results from the the direct query and php page return the same number of rows.
I have also tried:
SELECT * FROM ecrtable WHERE (ecrChangeOwner = 'ecunningham' OR ecrInitByName = 'ecunningham').
What am I missing? I have more complex queries that run fine. Please tell me I'm just missing something stupid...

You really should be using prepared statements here, first of all. You are wide open to injection attacks.
Second, how do you know that this query does not return all the rows? What queries have you done to verify that this one is wrong?
If you run a union what do you get:
SELECT * FROM ecrtable WHERE ecrChangeOwner = 'ecunningham'
UNION ALL
SELECT * FROM ecrtable WHERE ecrInitByName = 'ecunningham')

Related

How to get max of an ID as a PHP variable and insert it into another table where the ID is also max

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.

How to get result from mysql that contains in variable?

I'm not getting the result I need and I'm sure it is a small problem here.
I have a column(mfg_req) in my database which have a record with 10M.
My variable in php does have the text 10M40SABCDE.
What I want is to search in my table and get the results starting with this variable.
My MYSQL query does look like below but no results:
SELECT * FROM specific_req WHERE mfg_req LIKE '10M40SABCDE%'
I also tried the below query but no results
SELECT * FROM specific_req WHERE mfg_req LIKE '%10M40SABCDE%'
Also tried the below but it shows me all records except the one I need with 10M
SELECT * FROM specific_req WHERE '10M40SABCDE' LIKE CONCAT('%',mfg_req)
I have tried to put the % behind mfg_req but then it will show me all records including the one I need.
I cannot figure it out how to get the result I need. If someone can help me with my query I would appreciate it a lot.
Thanks!
Let's say:
$var = '10M40SABCDE';
...then your SQL statement must be:
$sql = "SELECT * FROM specific_req WHERE mfg_req LIKE '{$var}%'";
It would be best if you show a snippet of your code, too.

Write a query manually into the laravel

I have a little problem, I want to try to take the data with a custom query on laravel but when I try foreach I can't get the data. anyone can help me
This script on the controller :
$data = DB::Statement('SELECT NM_PERUSAHAAN,
count(*) as total_count,
sum(FLAG_TERIMA) as approved,
sum(1 - FLAG_TERIMA) as not_approved
from MSTBEASISWAS
group by NM_PERUSAHAAN;');
foreach ($data as $datas) {
echo $datas;
}
Error :
Here is the difference
DB::raw()
It generates a raw and sanitized SQL string, to be passed to other query/statements, preventing SQL injections. Is to be used with all of the and never alone. And you should never send a not sanitized string to your query/statements.
DB::select(DB::raw('select * from whatever'));
DB::select()
Is for simple selects:
DB::select(DB::raw('select * from whatever'));
DB::statement()
I think it work with selects, but should be used for non SQL query commands:
DB::statement(DB::raw('update whatever set valid = true;'));
DB::unprepared()
All SQL commands in Laravel are prepared by default, but sometimes you need to execute a command in an unprepared mode, because some commands in some database cannot be ran in prepared mode. Here's an issue I opened about this:
https://github.com/laravel/framework/issues/53
DB::unprepared(DB::raw('update whatever set valid = true;'));
Ref: Difference between Laravel's raw SQL functions
The DB::statement() method is used to execute SQL statements without returning result instead return true/false.
You're trying to use this boolean as a query result that why you've this message back from the foreach loop, if you want to run a select statement, you could use DB::select(), e.g :
DB::select('select query here');
Hope this helps.
You can write custom query like:
$data = DB::select(DB::raw('your query here'));
You can do as follows :
$data = DB::select($your_select_query);
The "statement" method of the DB facade returns a boolean value, which tells you whether the query execution was successful or not. Therefore foreach can not process it and throws an exception.
You can understand this by looking at the 2nd line of the exception stack trace.
array('data' => true)
So, to run a raw query string use the following code:
DB::select(DB::raw('SELECT NM_PERUSAHAAN,
count(*) as total_count,
sum(FLAG_TERIMA) as approved,
sum(1 - FLAG_TERIMA) as not_approved
from MSTBEASISWAS
group by NM_PERUSAHAAN;'));
DB::statement will not return data. if you are performing queries which don't return data, then using a SELECT query will result errors. For example, if you want to start the auto-increment ID of a MySQL table to something other than zero, we can use the statement method.
for the above query you have to use DB::select.
$data=DB::Statement('SELECT NM_PERUSAHAAN,
count(*) as total_count,
sum(FLAG_TERIMA) as approved,
sum(1 - FLAG_TERIMA) as not_approved
from MSTBEASISWAS
group by NM_PERUSAHAAN;');

Query different MySQL tables from PHP

been googling for hours and I'm quite new to this.
I have two identical tables in one MySQL database:
One named "users" and one named "keys".
They are identical for testing purposes.
When I query "users" I get a response, when I query "keys" I get nothing.
Querying users I get the expected response:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT name
FROM users
WHERE can_share = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
Querying keys I get nothing:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT name
FROM keys
WHERE can_share = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
I guess there must be some basic understanding of databases that has slipped by me, but still, after hours of searching I can't figure it out. Maybe I'm becoming retarded.
I think that might be due to table name being 'keys'.
Have a look here:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
You have to understand while designing your tables and naming the attributes that some words are reserved by MySQL itself.
So, if you name your table 'WHERE' you will have troubles in usual query. Why?
'SELECT * FROM WHERE'
Such a query obviously doesn't work, as it will ask you to provide table name.
Now, when you change format situation also changes:
'SELECT * FROM `WHERE`'
As you can see I added some backwards commas. In MySQL they are used to denote names of tables or fields. If you use them - the server processes and reads your query correctly.
So, that's why your edited query worked fine in the end.
Thanks to enabeling debugging, I got this message:
mysql_result() expects parameter 1 to be resource, boolean given in
...
And figured out that I had to query "keys" like this:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT `name`
FROM `keys`
WHERE `can_share` = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
Now it works, but I still don't understand why only one of the tables needed that formatting. And I have learned that I should rewrite the whole thing to not be vulnerable to SQL injection attacks. ...
EDIT: It seems like the words "key" and "keys" and some more are reserved by MySQL, so to use them, they have to be formatted like that.

UPDATE sql query and get the updated field in one single query

I'm trying to update a value of a column using the codeigniter query function like this:
$this->db->query("UPDATE table SET val = val + 1 WHERE name = 'xxxxx');
Is there any way to get the result of this update in the same query function? I have to do a select query in order to do it and it's dangerous because of the amount of users this application is managing.
If there is another query in between the update and the select, the result would not be correct.
Thanks!
Use transaction and for update. This is an example from zend, which is a similar kind of db accessing thing:
$db->beginTransaction();
$val = $db->select()->forUpdate()->from('table', 'val')->orderBy('val DESC')->limit(1)->query()->fetchColumn();
$db->update('table', 'val = '.($val+1), 'name = "xxx"');
$db->commit()
The for-update with the transaction prevents another query interfering.
Learn more about for update here: http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
and about codeigniter transactions here: http://ellislab.com/codeigniter/user-guide/database/transactions.html (thanks to #Nanne for that)

Categories