Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I would like to know how I can search a substring in all columns of a table when I do not know the names of the columns? Is there a foreach-loop-functionallity I do not know?
If I understand you correctly then this may work, brute forces a search through all the results.
Here is a PDO-based example:
$stmt = $dbh->prepare("SELECT * FROM table");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
foreach($row as $column){
if(strpos($column, "find me") !== false)
echo $match."found in:".$column."<br />";;
}
}
I am also lazy. I am also a ColdFusion programmer, not php. However programming logic is the same no matter what the language. I would do this:
Step 1 - Run this query and output the results somewhere
select *
from mytable
where 1 = 2
The outputted results will include the field names. Copy and paste then into your source code as a comment. Delete the ones that you are not going to query. Convert the remaining ones to a list variable. In ColdFusion, that list would look something like this:
listOfFields = "field2,field3,field8,etc";
Fields 1,4,5,6, and 7 were intentionally excluded. We are then going to loop through the list in our query. In ColdFusion, this would be the syntax
<cfquery>
select somefields
from sometables
where 1 = 2
<cfloop list="#listOfFields#" index = "thisField">
or #thisField# = something
</cfloop>
This meets the laziness criteria because you only have to get the field names once. Whether it's better or worse than getting the columns from the system tables and looping through them depends. Doing it this way will make your own app run faster because you don't have to query the system tables every time. However, if a new column is added to your table, you'll have to modify your source code to include it in your search.
If you do decide to query the system tables, make sure you only select char and varchar fields.
Adapt the sample query given at https://stackoverflow.com/a/1054988/1967396
SELECT *
FROM Northwind.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'Customers'
to get the names of the columns. Then loop over those names to search the table one column at a time for the specific strings. This takes advantage of the efficiency of SQL search and prevents you making a copy of the entire database just to search it (slowly) with nested foreach loops (as in #Silver89's answer).
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I want to execute a query to fetch data from 1000 rows in my database. I have found two methods to do that.
Method 1:
SELECT * FROM user WHERE id=879
and second one which I used to protect myself from SQL Injection was:
Method 2:
<?php
$q="SELECT * FROM user";
$get_res=$dbconn->query($q);
while($set=$get_res->fetch_assoc()) {
if($set['id']==879)
{
//Some task here
}
}
So Which one is faster. I know about SQL prepared Statement.. But I just want to compare these two method.. And if there will be any security flaw in Method2 then Please explain that one also..
If this is just static id=879 you can simply just execute the query. It's fast, performant, and lets MySQL do the filtering for you.
Method 1:
SELECT * FROM user WHERE id=879
Most performant, and is your choice if 879 is not a variable. Just execute the query, return 1 result.
Method 2:
$pdo = new PDO($dsn, $user, $pass, $opt);
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([ $_POST['user_id'] ]);
$user = $stmt->fetch();
This method uses PDO (alternatively you can use bind_param that's available in the MySQLi package). Return 1 result from the database, and safely bind the variable to the query string for execution. This is likely your best solution, as it lets MySQL do the filtering (Using indexes and the most efficient means to find your result).
Method 3 (DO NOT USE):
<?php
$q="SELECT * FROM user";
$get_res=$dbconn->query($q);
while($set=$get_res->fetch_assoc()) {
if($set['id']==879)
{
//Some task here
}
}
HORRIBLE! You are returning EVERY result from the database, and causing many many needless loops to grab the data you want. Let the database do the filtering, it's what it was designed for!
The first (SQL) method is faster.
Reason: SQL is designed for filtering the rows (using the id) very fast. Thus it first searches through all the indexes and returns a single, matching result.
Despite this, with PHP this does the logically the same, but PHP has to fetch the complete row first, validate the id, and proceed to the next row if it does not match.
Both are sql querys, only that in the second one you're using php to make the query instead of doing directly as in the first one.
If it's a webpage what you're building, you need to do it rather with php or jsp, because you can't do it directly in this scenario.
However if you're asking which one is faster, it's the first one with no doubts. However it's use is limited to SQL platform rather than globally with php.
I assume in the first method you're still using PHP to execute the query.
If you're taking in user input, then in no way is the second method protecting you from SQL injection. You'll need parameterized queries for that.
Also, method 1 is definitely the way to go - the more closely you can get to the desired result without PHP, the better.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a little problem, am trying to read values from mysql table. I have done research and could not find a definite or conclusive answer on this. I will describe the problem:
select data from mysql table using a where e.g where gender=female.
count the results and return the count - just to help know how many records were found
compare a value in table, e.g 'taken' and 'available',
if 'taken' = 'available' in the first record, go to next record(and compare again), if not perform a specific operation in this case can be update or insert or anything of that sort.
the first three are ok and the only problem is, part 4. Kindly help. This is a php problem. Looking forward for your help.
As was said, if you're merely going to skip the record then you may as well not retrieve them in the first place (and thus incur the overhead for having to extract them into PHP memory, etc):
SELECT * FROM `your_table` WHERE `gender` = 'female' AND `taken` = `available`;
However, if you have a specific reason to do this, you can merely do the following:
foreach ($hotels as $hotel) {
// skip if the item is not available, logic can be changed if necessary
if ($hotel->taken >= $hotel->available) continue;
// do the other work here...
}
I interpreted your conditions a little here, assuming you wanted to skip people who aren't 'available'. Though it does look like you wanted the opposite, in which case you can switch the logic in the sql from != to = and in php from != to ==.
Updated: To reflect additional comments made.
Create connection to your database using mysqli or by using PDO.
$db = new PDO($mysqlhost,$username,$password);
$statement = $db->prepare($sqlstatement);
$rows = $statement->execute();
foreach($rows->fetch() as $row)
{
if($row['column_name']==something)
{
//do work
}
else
{
//do work
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm quite new to MySQL, so don't judge! Anyhow, what I'm trying to do is store the 10 newest rows in a MySQL database into a PHP array. My variable $news contains the MySQL data I got from running the fetch_news() query (which I told only to grab content that has a column called type with the value "news" in it). However, I've been unable to do this successfully.
If you guys could offer some help, or guidance, it'd be much appreciated as I have been stuck on on this for quite some time now!
$query = 'SELECT *
FROM `table_name`
WHERE `type`="news"
ORDER BY `article_id` DESC
LIMIT 10';
$query = mysqli_query($link, $query);
$result = array();
while ($row = mysqli_fetch_assoc($query)) {
$result[] = $row;
}
print_r($result);
$newest_ten = array();
$command = "select * from table_name order by date DESC limit 10";
$result = $db->query($command);
while($data = $result->fetch_assoc()){
$newest_ten[] = $data;
}
The command is getting all columns from the table table_name, putting them in order based on their date (so newest to oldest), and then only giving you the first ten of those.
The while loop goes through the results and adds them to an array.
While your "type" column tells you if the row is a news item or not, it doesn't tell you anything about when it was added to the table.
You need to use some other column as well, either some sort of incremental counter (like the "article_id" might be), or a time stamp when the item was added to your table (this is probably the "article_timestamp" in your case).
With one of those you can sort the results the way you want.
When you have sorted your results, you need to limit them to just the 10 you want.
You can find more information about ORDER BY and LIMIT in the Official MySQL documentation.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is there any simplification for this?
$query = $this->link->prepare('SELECT * FROM test WHERE id = :id LIMIT 1')
$query->bindParam(':id', $id);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
unlink($row['avatar']);
$query = $this->link->prepare('DELETE FROM test WHERE id = :id LIMIT 1');
$query->bindParam(':id', $id);
$query->execute();
I don't like to advise people to skip using query parameters. You should get into the habit of doing it.
It's actually not hard, and it makes it simpler to write queries because you never have to think about whether you got the right kind of escaping and quoting. I find it makes my code look more clear.
I've always been puzzled how people learn that they need to use bindParam() for everything with PDO. It's simpler in most cases to pass an array of parameters to execute(). The only case when I typically use bindParam() is if I need to pass a NULL value.
Also you don't need to use named parameters, you can use positional parameters (but don't mix these parameter types in a given query).
fetchColumn() is simpler if you only need one column. Speaking of which, avoid SELECT * when you don't need all the columns.
If you are querying for a specific id, assuming that's the primary key, then you don't need LIMIT 1. There can be at most one row for a specific value in any unique key.
I assume you've enabled the exception-based error reporting. If not, you should check the result from each call to prepare() and execute() because they return false on error.
$query = $this->link->prepare('SELECT avatar FROM test WHERE id = ?')
$query->execute([$id]);
$avatar = $query->fetchColumn();
unlink($avatar);
$query = $this->link->prepare('DELETE FROM test WHERE id = ?');
$query->execute([$id]);
PS: The short syntax for arrays, like [$id], requires PHP 5.4
Thank you for the good question. To my utter disappointment, such questions are extremely rare on this site.
Is there any simplification for this?
Sure.
This is called "programming".
Although for the average PHP user programming stands for just putting several predefined blocks together, like LEGO bricks, in reality programming stands more for invention, for creating something new. And no less for optimizing too, for taking less moves for the same action.
A programmer could always create a function to encapsulate repeated tasks. Eventually he may wish to put such functions together into a class, but that's not the point.
As you can see, most of your operators just repeated ones. Every time you see a repetition you know for sure there can be a function or at least a loop.
Here is your code using my attempt in programming, aimed (beside extra safety) to the very code shortening:
$name = $this->link->getOne('SELECT avatar FROM test WHERE id = ?i', $id)
unlink($name);
$this->link->query('DELETE FROM test WHERE id = ?i', $id);
As you can see, this code is Extra DRY (stands for Don't Repeat Yourself) - all the repeated code is just taken away into internals.
Well, as you can see, my class is built upon mysqli. but of course something similar can be done even using ugly PDO, using wrapper sort of one I posted recently:
$name = $this->link->query('SELECT avatar FROM test WHERE id = ?', [$id], "one");
unlink($name);
$this->link->query('DELETE FROM test WHERE id = ?', [$id]);
By the way, taking programming little further you may shorten this code even more:
unlink($avatar_dir.$id.".png");
$query = $this->link->query('DELETE FROM test WHERE id = ?i', $id);
as avatar image obviously don't need no dedicated name and just id can serve perfectly, saving you extra field in database and extra query. All avatars can be converted to single format at the time of upload, to reduce the headache even more.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I usually try to have less MySQL queries possible in my projects, and then I format the datas using PHP.
I was wondering if the performances would be better with more MySQL queries which give me the exact data in the right format or if is better get all I need in a single query and then parse the result with PHP to get the Arrays I need.
In the modern PHP, where encapsulation is one of the main points while writing code, a bunch of queries won't be executed, if you explicitly don't call the methods, which do the job.
Against some old-procedural style, where you can have in one page 100 queries and testing with is..() functions, which query to use, you will have a high load to your engine, because of the runtime compilation.
Thus, you can afford youself as much conditions as you want in a lot of queries, and less PHP to test it.
Let's have an example with something small.
Assume, you have something like a model, for an item called "Article". You want a search either by id, author or name. There's nothing wrong to have this:
public function getArticleById($id) {
$sql = "SELECT id, name, author FROM article WHERE id = $id";
$query = $this->db->query($sql);
$result = $this->db->fetch($query);
return $result; //assuming you have query and fetch method, where the last one return an array/object
}
public function getArticleByName($name) {
$sql = "SELECT id, name, author FROM article WHERE name = $name";
$query = $this->db->query($sql);
$result = $this->db->fetch($query);
return $result;
}
public function getArticleByAuthor($author) {
$sql = "SELECT id, name, author FROM article WHERE author = $author";
$query = $this->db->query($sql);
$result = $this->db->fetch($query);
return $result;
}
Depends on what you want, you can use one of these methods. I usually asume, you can reuse the information returned by these methods in more than one page, because it returns the whole needed information for a single Article for example. On the other hand, I would assume you have used some bad practices, if, for example, the article has a DateTime field, and you use it in 3 pages with different formats - then you will need PHP to reformat the datetime, each time you use the method, which returns the info, and will be total overkill if you have 3 queries, which returns the datetime with different formats.
Also, total overkill is to request the whole table, and filter the information with PHP, instead of WHERE:
public function getArticle() {
$sql = "SELECT id, name, author FROM article";
$query = $this->db->query($sql);
$result = $this->db->fetch($query);
return $result;
}
//...
foreach ($model->getArticle() as $article) {
if ($article['name'] == $name) {
//...
}
Talking about performance is subjective thing, it really matters how and how often you query the database, so a single query which formats the data in given manner is reused often enough, you won't load your core.
As a rule of thumb..
Usually, the rule I go by is to try to minimize the amount of requests you're making to some sort of persistent structure, like a Database. Database requests are very fast, but letting a language manipulate structures in memory is usually faster. It also depends on just how busy your DBMS is. Are there other people requesting from this table? Is it just you? Will it always be just you using it?
If you want..
You could do some benchmark tests, and simply time how long it takes for two threads to finish. One with the multiple MySQL queries; one with the single MySQL query. If you see a noticeable and consistent difference, then you've got your answer!