i got this code
while ($aResult = mysql_fetch_array($result))
{
$sResult[$aResult[userID]] = $aResult;
}
but i want to know is there a faster way to put everything from $aresult in the sresult global?
It depends on the definition of "faster". If you want minimum CPU usage, you propably should use the function above, or as Col. said, try to avoid fetching all and use pointers.
If you want less coding time, consider using a a wrapper such as PEAR DB. With it you can just write $res = $db->getAll( $SQL );
http://pear.php.net/manual/en/package.database.db.db-common.getall.php
Related
I want delete values of less than two characters from a my large array which have 9436065 string values. I deleted with preg_grep() using this code:
function delLess($array, $less)
{
return preg_grep('~\A[^qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM]{'.$less.',}\z~u', $array);
}
$words = array("ӯ","ӯро","ӯт","ғариб","афтода","даст", "ра");
echo "<pre>";
print_r(delLess($words,2));
echo "</pre>";
But it works slower. Is it possible to optimize this code?
I would go for array_filter function, performance should be better.
function filter($var)
{
return strlen($var) > 2;
}
$newArray = array_filter($array, "filter"));
given the size of the dataset, I'd use a database, so it would probably look like this:
delete from table where length(field) <= 2
maybe something like sqlite?
You could try using the strlen function instead of regular expressions and see if that is faster. (Or mb_strlen for multibyte characters.)
$newArr = array();
foreach($words as $val)
if(strlen($val) > 2)
$newArr[] = $val;
echo "<pre>";
print_r($newArr);
echo "</pre>";
Any work on 10 million strings will take time. In my opinion, this kind of operation is a one timer, so it does not really matter if it is not instantaneous.
Where are the strings coming from? You certainly got them from a database, if so, do the work on the database it will be faster and at least you will not be polluted with them ever. This kind of operation will be faster on a database than PHP, but could still take time.
Again, if it is stored in a database, it has not got there magically... So you could also make sure that no new unwanted entry gets in it, that way you make sure this operation will not need to be redone.
I am aware that this absolutely does not answer your question at all, because we should stick to PHP and you got the best way to do it... Optimizing such a simple function would cost a lot of time and wouldn't bring much if any optimization... The only other suggestion I could make is use another tool, if not database-based, file-based like sed, awk or anything that reads/writes to files... You'd have one string per line and parse the file reducing its size accordingly, but writing the file from PHP, exec the script and load the file back in PHP would make things too complicated for nothing...
say I had this
$src = "function($message) { echo $message; }"
I'm looking for a way to turn the source as a string into an actual function during runtime, sorta like
$say_message = magic_command($src);
$say_message("hello");
but I haven't found a way to do it.
If you're pondering the purpose, I'm extracting data from a large string. To make it simpler to change the procedure, I created an intermediary language(regex really won't do here) which I'm just eval'ing right now. I figured turning the procedure into a php native function might speed up the processing.. worth a shot. Security is not a concern, I'm the only one using this.
$src = '$say_message = function($message) { echo $message; };';
eval($src);
$say_message("hello");
This is the actual way to get $say_message to work as a function through string, you have to use eval(), make sure you add the proper ; in the code
There is also another way to create it but not from a single string, using create_function()
$say_message = create_function('$message','echo $message;');
$say_message("hello");
I've developed a habit of renaming my SELECT statement variable and I'm interested to know if it is necessary or not.
Here some typical code that I use:
$sql = ("SELECT * FROM tbl_one");
if(!$result_sql = $mysqli->query($sql))
{
// Error code here
}
while($a = $result_sql->fetch_assoc())
{
echo $a;
}
$sql2 = ("SELECT * FROM tbl_two");
if(!$result_sql2 = $mysqli->query($sql2))
{
// Error code here
}
while($b = $result_sql2->fetch_assoc())
{
echo $b;
}
For some reason I'm afraid there will be issues if I reuse the same $sql variable over again unless I rename it.
It's always good to have a different different variable for each statement you have as per coding standards even though PHP does not mind using same variable again and again.
It's just a string, so you shouldn't care. Its fine to use the same variable again if you don't need the previous value anymore.
Theoretically I opt not to reuse variable names for this sort of code, because of the risk of accidentally not overwriting one of them and getting strange results.
Then again, that problem doesn't go away just because you try to force yourself to remember to increment a number stuck on the end of the variable name.
Over time, as my code has improved, I've found that I very rarely need or want to execute multiple MySQL queries within a single PHP function, so the problem goes away entirely.
tl;dr: If I had a gun to my head, though... yes, I'd probably do it the same way you did. It's entirely subjective, though.
So, if I want to pull some data from my database (PHP, MySql), whether I'm writing for a class or hard-coded, I've been doing something along the lines of:
$x = "SELECT <column(s)> FROM <table> WHERE <conditions>";
$y = mysql_query($x);
while($result = mysql_fetch_assoc($y))
{
echo $result['column']; // etc
}
Obviously I use a function or class (depending on design pattern) so pulling data like this is done in one line, I just wondered if I was doing 'too much work' and if there was a quicker way of doing this.
Thanks.
You can get tighter code by using a more up-to-date PHP module to access your database.
The mysql_xxx() functions that you're using have been superseded by the mysqli_xxx() functions. This uses similar code, but provide more features and security than the older library:
$query = 'SELECT <column(s)> FROM <table> WHERE <conditions>';
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
print $row['column'];
}
}
You can find out more about MySQLi (including how it differs from the old MySQL library) here: http://php.net/manual/en/book.mysqli.php
But for really concise code, you might consider looking into the PDO library. Your query could be expressed with PDO like this:
$sql = 'SELECT <column(s)> FROM <table> WHERE <conditions>';
foreach ($conn->query($sql) as $row) {
print $row['column'];
}
...and if you really wanted to, the first two lines of that code could be combined as well.
Find out more about PDO at the PHP manual site: http://www.php.net/manual/en/book.pdo.php
Looks good. you maybe can merge the first tow lines into "$y = mysql_query('SELECT FROM WHERE ');"
And notice that in PHP its faster (from compile time) to use single quotes (') rather that double quotes (").
It depends on the further work, but you might wanna consider loading the info into XML dom format. (If you want to do more sophisticated things that just representing the data)
Which one of these two is better in my case?
While loop:
function search_hotel($searchterm)
{
$query = $this->db->order_by("id", "desc")->like('name', $searchterm)->get('hotel_submits');
$data = array();
while($row = mysql_fetch_array($query))
{
$data[] = $row->name;
}
return $data;
}
Foreach loop:
function search_hotel($searchterm)
{
$query = $this->db->order_by("id", "desc")->like('name', $searchterm)->get('hotel_submits');
$data = array();
foreach ($query->result() as $row)
{
$data[] = $row->name;
}
return $data;
//return mysql_query("select * from hotel_submits where name LIKE '".$searchterm."'");
}
while is technically more efficient than foreach, but it's not worth comparing: they're both pretty much identical in this case.
In your case, result returned by query is array. Which means you can use foreach statement or while statement.
Just note that foreach statement is optimized for working with arrays (and as of PHP5, objects as well) and is faster than while statement. While can be used to achieve the same effect but it is not as efficient if you want to go through all elements of the array.
When using a framework and its custom DB adapter class, it seems pointless to switch back to PHP's built-in functions in the middle of a script. Even if CI's adapter and PHP's mysql_* functions might be using the same DBMS connection library (mysql).
I strongly recommend to stick with Code Igniter's version (foreach ($query->result() as $row)). From a performance point of view, there shouldn't be any noticeable differences. Regarding the application architecture, it certainly is much cleaner not to mix the access interfaces. Although it might work out, it might also cause problems.
It would appear you're mixing up mysqli and mysql syntax. The two libraries are NOT compatible internally. You cannot use a handle/statement in one and consume it in another. Both libraries maintain completely independent connections to the database.
That'd mean the first one will be faster, since mysql_fetch_array() will fail and the inner loop will never run. But faster doesn't mean "right".