Limit fetched data from db into a list in HTML - php

I'm working on a autosuggest field and it works already. The only thing I'm trying to do now, is to limit the output of data in the list below the search field.
Can someone help me how to do it? I tried a few ways already, but ending up with errors. So what I'm trying is to limit the amount of results which get pulled out of the database. I tried doing this in php (I think it's better performance wise, isn't it?). Here's the code that works fine already:
<?php
require_once 'connect.php';
if (isset($_POST['search_term']) == true && empty ($_POST['search_term']) == false) {
$search_term = mysql_real_escape_string ($_POST['search_term']);
$query = mysql_query ("SELECT `word` FROM `datalist` WHERE `word` LIKE '$search_term%'");
while (($row = mysql_fetch_assoc($query)) !==false) {
echo '<li>', $row['word'], '</li>';
}
}
?>
Since I'm not an expert, I would be happy for some help to learn more...

You can limit it in your query. It would be better to limit the amount of data you retrieve from the database, rather than retrieve everything and then filter the results later. MySQL is built to run these query's quickly, so use it to your advantage.
mysql_query ("SELECT `word` FROM `datalist` WHERE `word` LIKE '$search_term%' LIMIT 5");
However you can do it in php if you want by fetching in a for loop:
$limit = 5 // Make limit whatever you want
// Make sure you have enough results to fetch
if(mysql_num_rows($query) < $limit)
$limit = mysql_num_rows($query);
for($i = 0; $i < $limit; $i++){
$row = mysql_fetch_assoc($query);
echo '<li>', $row['word'], '</li>';
}

The easiest approach would be to update your sql query and add a limit clause. So if you maybe want only the first 10 results, do it like this:
SELECT `word`
FROM `datalist`
WHERE `word`
LIKE '$search_term%'
LIMIT 10;
You can do that in php without modifying your query, too, but I found it easiest if you just pull from the database what you need.
By the way, you're using the old mysql connector. This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.

Related

Displaying users with a php, sql count?

I have a database with users input and was wanting to output a user table (id, username) as a count on a page. The following piece of code is what I've been trying to work with but I've been having no luck and it keeps getting more and more complex - the SQL works perfectly so I'm not sure what's wrong.
mysqli_select_db($db);
$result = $_POST ['$result'] ;
$result = mysqli_query("SELECT COUNT( * )
FROM users");
$row = mysqli_real_escape_string($result,$db);
$total = $row[0];
echo "Total rows: " . $total;
I'm still learning how to properly link SQL in with PHP. The warnings tell me to add an extra parameter however when I do so it still complains.
I originally wanted a simple COUNT but will change the count to a table array if need be. I understand this maybe a little basic and I may have been going about it the wrong way, but I've hit a wall with it and any help on fixing the COUNT would be greatly appreciated
Replace the call to mysqli_real_escape_string to mysqli_fetch_array and your code will works.
mysqli_real_escape_string is only useful for string escaping when you INSERT or UPDATE data to MySQL.
$row = mysqli_fetch_array ($result);
Please try this code:
$sql="SELECT * FROM users";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
$number = count($rows);
Hope this works.

For-loop not returning all values

I'm working on a piece of code that's meant to be implemented in Google Charts, however, not all values I'm looking for are being returned.
I need a couple of dates selected from my database, and I select them as follows:
$dates = mysql_fetch_row(mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'")) or die(mysql_error());
Then I use a for-loop to echo them:
for ($i = 0; $i <= count($dates); $i++)
{
echo $dates[0].' ';
}
In my database there are 3 (distinct) dates: 24-03-2013, 25-03-2013 and 26-03-2013, however the piece of code returns 2x 24-03-2013. What am I doing wrong here?
P.S. I also tried a while-loop but that loops infinitely or crashes my page. Besides that, I tested the query by running it in the database itself and it returns the right results, so the query works fine.
Help is much appreciated!
You need to use mysql_fetch_row() inside a loop in itself:
$result = mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'");
while($date = mysql_fetch_row($result))
{
echo $date[0];
}
You should also note that the mysql_* family of functions are not deprecated. You should avoid using them if possible, and look into alternatives such as MySQLi or PDO.
Try this: mysql_fetch_row() fetches only one row, If you need all the rows use mysql_fetch_assoc()
$sql = mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'");
while($dates = mysql_fetch_assoc() ($sql)){
print_r($dates);
}
Ref: http://php.net/manual/en/function.mysql-fetch-row.php
http://www.php.net/manual/en/function.mysql-fetch-assoc.php
mysql_fetch_row only returns one record from the actual result of your query. You have to call it several times, ontil it returns null :
$res = mysql_query(...);
while (($record = mysql_fecth_row($res)) !== null) {
print_r($record[0]);
}
Please note mysql_* function are deprecated and should not be used anymore, too.

php request of mysql query timeout

i'm trying to make a long mysql query and process and update the row founded:
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
$result = mysql_query($query);
$total = mysql_num_rows($result);
echo $total;
while ($db_row = mysql_fetch_assoc($result))
{
//process row
}
but after 60 second give me a timeout request, i have try to insert these in my php code:
set_time_limit(400);
but it's the same, how i can do?
EDIT:
only the query:
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
takes 2-3 second to perform, so i think the problem is when in php i iterate all the result to insert to row or update it, so i think the problem is in the php, how i can change the timeout?
EDIT:
here is the complete code, i don't think is a problem here in the code...
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
$result = mysql_query($query);
$total = mysql_num_rows($result);
echo $total;
while ($db_row = mysql_fetch_assoc($result)) {
//print $db_row['id_show']."-".$db_row['actors']."<BR>";
$explode = explode("|", $db_row['actors']);
foreach ($explode as $value) {
if ($value != "") {
$checkactor = mysql_query(sprintf("SELECT id_actor,name FROM actors WHERE name = '%s'",mysql_real_escape_string($value))) or die(mysql_error());
if (mysql_num_rows($checkactor) != 0) {
$actorrow = mysql_fetch_row($checkactor);
$checkrole = mysql_query(sprintf("SELECT id_show,id_actor FROM actor_role WHERE id_show = %d AND id_actor = %d",$db_row['id_show'],$actorrow[0])) or die(mysql_error());
if (mysql_num_rows($checkrole) == 0) {
$insertactorrole = mysql_query(sprintf("INSERT INTO actor_role (id_show, id_actor) VALUES (%d, %d)",$db_row['id_show'],$actorrow[0])) or die(mysql_error());
}
} else {
$insertactor = mysql_query(sprintf("INSERT INTO actors (name) VALUES ('%s')",mysql_real_escape_string($value))) or die(mysql_error());
$insertactorrole = mysql_query(sprintf("INSERT INTO actor_role (id_show, id_actor, role) VALUES (%d, %d,'')",$db_row['id_show'],mysql_insert_id())) or die(mysql_error());
}
}
}
}
Should definitely try what #rid suggested, and to execute the query on the server and see the results/duration to debug - if the query is not a simple one, construct it as you would in your PHP script, and only echo the SQL command, don't have to execute it, and just copy that in to the server MySQL command line or whichever tool you use.
If you have shell access, use the top command after running the above script again, and see if the MySQL demon server is spiking in resources to see if it really is the cause.
Can you also try a simpler query in place of the longer one? Like just a simple SELECT count(*) FROM tvshows and see if that also takes a long time to return a value?
Hope these suggestions help.
There are so many problems with your code.
Don't store multiple values in a single column. Your actors column is pipe-delimited text. This is a big no-no.
Use JOINs instead of additional queries. You can (or could, if the above weren't true) get all of this data in a single query.
All of your code can be done in a single query on the server. As I see it, it takes no input from the user and produces no output. It just updates a table. Why do this in PHP? Learn about INSERT...SELECT....
Here are some resources to get you started (from Googling, but hopefully they'll be good enough):
http://www.sitepoint.com/understanding-sql-joins-mysql-database/
http://dev.mysql.com/doc/refman/5.1/en/join.html
http://dev.mysql.com/doc/refman/5.1/en/insert-select.html
What is Normalisation (or Normalization)?
Let me know if you have any further questions.

Use a PHP function on MySql Column

I have 4 columns in my database. Atk,Str,Dex,and Con. Each being INT and then I have a PHP function get_level that takes those 4 columns and determines the correct level for them. I'm trying to select all users in a given range based on these "levels". The get_combat function takes those 4 values and finds the users combat level. This is what I have, which doesn't work.
<?PHP
$query = "SELECT get_level(attack) as atk,
get_level(strength) as str,
get_level(dexterity) as dex,
get_level(constitution) as con,
get_combat(atk,str,dex,con) as level
FROM `users`
WHERE level > 5 AND level < 10";
?>
Is there a way to do this?
What you are trying to do is impossible. MySQL doesn't even know what PHP is or which language is talking to it.
Why not fetch the values and call your function on in in the loop where you iterate over the results?
Depending on how complex the function is you could also create a stored procedure in your database. You cannot write PHP code in that function though.
I think you can't do something like this in SQL. After executing the query you can use the functions. Assuming you are using the old mysql_* functions:
<?php
$result = mysql_query($query);
$newResults = array();
$i = 0;
while( $row = mysql_fetch_assoc($result) ) {
$newResults[$i]['atk'] = get_level($row['attack']);
$newResults[$i]['strength'] = get_level($row['strength']);
/** ect. **/
$newResults[$i]['level'] = get_combat($newResults['atk'],$newResults['str'],$newResults['dex'],$newResults['con']);
}

PHP PDO Buffered query problem

I'm having some serious problems with the PHP Data Object functions. I'm trying to loop through a sizeable result set (~60k rows, ~1gig) using a buffered query to avoid fetching the whole set.
No matter what I do, the script just hangs on the PDO::query() - it seems the query is running unbuffered (why else would the change in result set size 'fix' the issue?). Here is my code to reproduce the problem:
<?php
$Database = new PDO(
'mysql:host=localhost;port=3306;dbname=mydatabase',
'root',
'',
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
)
);
$rQuery = $Database->query('SELECT id FROM mytable');
// This is never reached because the result set is too large
echo 'Made it through.';
foreach($rQuery as $aRow) {
print_r($aRow);
}
?>
If I limit the query with some reasonable number, it works fine:
$rQuery = $Database->query('SELECT id FROM mytable LIMIT 10');
I have tried playing with PDO::MYSQL_ATTR_MAX_BUFFER_SIZE and using the PDO::prepare() and PDO::execute() as well (though there are no parameters in the above query), both to no avail. Any help would be appreciated.
If I understand this right, buffered queries involve telling PHP that you want to wait for the entire result set before you begin processing. Prior to PDO, this was the default and you had to call mysql_unbuffered_query if you wanted to deal with results immediately.
Why this isn't explained on the PDO MySQL driver page, I don't know.
You could try to split it up into chunks that aren't big enough to cause problems:
<?php
$id = 0;
$rQuery = $Database->query('SELECT id FROM mytable ORDER BY id ASC LIMIT 100');
do {
stuff($rQuery);
$id += 100;
} while ( $rQuery = $Database->query(
'SELECT id FROM mytable ORDER BY id ASC LIMIT 100 OFFSET '.$id
)
);
?>
...you get the idea, anyway.
Or maybe you could try mysql functions instead:
while ($row = mysql_fetch_row($query)) {
...
}
Which will definitely be faster, since that foreach statement makes an impression to use fetchAll() instead fetch() each row

Categories