I tried to use this function
$conn = db_connect();
while ($newsfeed = $conn->query("select info, username, time from newsfeed ORDER BY time DESC LIMIT 10"))
{
(...)
echo "<p>User $newsfeed_username just registerted ".$minutes." min ago </p><br>";
but it only shows the latest row over and over again. I want to loop through all the queries from
select info, username, time from newsfeed ORDER BY time DESC LIMIT 10
in descending order.
Here's the basic template for this kind of thing, using built-in php functions (assuming old-style mysql, but similar using other database back-ends, or higher-level libraries). In this example, errors are handled by throwing exceptions, but that's just one way to do it.
Connect to the database
Make sure connection was successful
Run the query
Make sure the query didn't fail for some reason (usually a SQL syntax error). If it did fail, find out why and handle that error
Check that the query returned at least one row (zero rows typically is a special case)
Loop over the returned rows, doing whatever it is you need done.
The exception classes would need to be defined (they're the only non-built-in syntax here, but you shouldn't throw plain-vanilla Exceptions).
Example Code:
<?PHP
//try to connect to your database.
$conn = mysql_connect(...);
//handle errors if connection failed.
if (! $conn){
throw new Db_Connect_Error(..);
}
// (try to) run your query.
$resultset = mysql_query('SELECT ...');
//handle errors if query failed. mysql_error() will give you some handy hints.
if (! $resultset){
// probably a syntax error in your SQL,
// but could be some other error
throw new Db_Query_Exception("DB Error: " . mysql_error());
}
//so now we know we have a valid resultset
//zero-length results are usually a a special case
if (mysql_num_rows($resultset) == 0){
//do something sensible, like tell the user no records match, etc....
}else{
// our query returned at least one result. loop over results and do stuff.
while($row = mysql_fetch_assoc($resultset)){
//do something with the contents of $row
}
}
First you don't want to loop though queries. You want to loop through records which query will return.
Second you could do that, this way:
$conn = db_connect();
$query = mysql_query("SELECT info, username, time FROM newsfeed ORDER BY time DESC LIMIT 10");
while(($row = mysql_fetch_assoc($query)) != NULL) {
echo "<p>User {$row['username']} just registered {$minutes} min ago</p><br />";
}
NB! Assuming, that this db_connect() makes a mysql connection.
You need to store the result of $conn-query() in a variable before entering the loop. Right now you're running the query over and over again with each iteration of the loop which will always give you the first result.
Example
$conn = db_connect();
$result = $conn->query("select info, username, time from newsfeed ORDER BY time DESC LIMIT 10");
foreach ($result as $newsfeed)
{
(...)
echo "<p>User $newsfeed_username just registerted ".$minutes." min ago </p><br>";
Related
So i'm working with huge MYSQL database of english words. the list has upwards of 180k words. Im trying to run a query, and then compute something using every word in the database. The problem is the database is so big, and it seems to be freezing my browser (Im working locally with MAMP). Is there a way I can do five queries at a time, instead of trying to run through the whole thing, so i can see the results coming in gradually in my browser? Heres the code:
<?php
require 'class.thing.php';
require 'db_config.php';
$result = mysql_query("SELECT * FROM words") or die ("Could not complete query");
while($row = mysql_fetch_array($result))
{
$word = $row['word'];
$compute = $word."thing";
$finished = new method( $compute );
if ($finished->successfull()) {
echo "<br/>";
echo "worked!";
echo "<br/>";
} else {
echo "uh oh..";
}
}
?>
** im looking for something like:
$result = mysql_query("SELECT * FROM words") or die ("Could not complete query LIMIT 0,5");
get results
wait 5 seconds
$result = mysql_query("SELECT * FROM words") or die ("Could not complete query LIMIT 0,5");
get results
etc...
You should take a look at this related question:
What is the best way to paginate results in SQL Server
Note that you can compare words in SQL alphabetically (check whether your settings use case sensitive sorting or not), so you can do something like:
SELECT * FROM words WHERE word <= "ferrous" ORDER BY word
If you're using an auto-incrementing id, you can use that to subdivide as well (it'd probably be easier).
EDIT:
As pointed out below, you can use LIMIT in MySQL.
Example:
SELECT * FROM words LIMIT 0, 1000
(This would display the first 1000 results).
Why won't this query work?!?
Error
Parse error: syntax error, unexpected T_STRING in E:\xampp\htdocs\pf\shop\buy.php on line 5
Example Info For Variables
$character->islots = 20
$chatacter->name = [RE] Tizzle
$e2 = 10
The Function
function increaseSlots($e2) {
$slots = ($character->islots)+($e2);
mysql_query('UPDATE `phaos_characters` SET `inventory_slots`="'.$slots.'" WHERE `name`="'.$character->name.'"'); // <-- Line 5
if (mysql_affected_rows() != 0) {
echo 'Inventory Size Incresed By '.$e2.' Slots';
}else{
echo mysql_error();
}
}
Look at the docs: http://php.net/manual/en/function.mysql-num-rows.php
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
You need to use mysql_affected_rows() or better yet, PDO or mysqli.
$slots = ($character->islots)+($e2);
Looks like there is a typo. Try:
$slots = ($character->slots)+($e2);
First off you should know that mysql_num_rows only returns a valid result for SELECT or SHOW statements, as stated in the PHP documentation. You can use mysql_affected_rows() for your particular needs.
However, the old PHP MySQL API (that you are using) is being phased out, so I would recommend using mysqli or PDO for your DB connection needs.
While keeping with your requirements, though, you can try to use the following syntax to make sure you receive the MySQL error if it throws one. Your PHP script will stop, but you will see the error.
$query = sprintf('UPDATE `phaos_characters` SET `inventory_slots`=%d WHERE `name`="%s"',$slots,$character->name)
$result = mysql_query($query) or die(mysql_error());
As a final idea, in situations like this it helps to print out your resulting $query and run it manually through something like phpMyAdmin to see what happens.
Bleh... I Found a better way to do it for the time being.. sorry to waste your guys' time...
I just threw the $character object into a variable before processing the function.
function increaseSlots($e2,$charname,$charslots) {
$slots = $charslots+$e2;
mysql_query('UPDATE `phaos_characters` SET `inventory_slots`="'.$slots.'" WHERE `name`="'.$charname.'"');
if (mysql_affected_rows() != 0) {
echo 'Inventory Size Incresed By '.$e2.' Slots';
}
}
I want to show all text messages from db where id=$e ($err is an array).
Inserted the query into the foreach loop, it works well but it does extra work (does query for every value of array).
Is there any other way to do it (i mean extract query from foreach loop)?
My code looks like this.
foreach ($err as $e)
{
$result = $db -> query("SELECT * from err_msgs WHERE id='$e'");
$row = $result -> fetch_array(MYSQLI_BOTH);
echo "<li><span>".$row[1]."</span></li>";
}
It is much more efficient to do this with implode() because it will only result in one database query.
if (!$result = $db->query("SELECT * FROM `err_msgs` WHERE `id`='".implode("' OR `id`='",$err)."'")) {
echo "Error during database query<br />\n";
// echo $db->error(); // Only uncomment this line in development environments. Don't show the error message to your users!
}
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
echo "<li><span>".$row[1]."</span></li>\n";
}
Check the SQL IN clause.
Firstly, a bit of a lecture: embedding strings directly into your queries is going to cause you trouble at some point (SQL injection related trouble to be precise), try to avoid this if possible. Personally, I use the PDO PHP library which allows you to bind parameters instead of building up a string.
With regard to your question, I'm not sure I have understood. You say that it does extra work, do you mean that it returns the correct results but in an inefficient way? If so then this too can be addressed with PDO. Here's the idea.
Step 1: Prepare your statement, putting a placeholder where you currently have '$e'
Step 2: Loop through $err, in the body of the loop you will set the place holder to be the current value of $e
By doing this you not only address the SQL injection issue, you can potentially avoid the overhead of having to parse and optimise the query each time it is executed (although bear in mind that this may not be a significant overhead in your specific case).
Some actual code would look as follows:
// Assume that $dbdriver, $dbhost and $dbname have been initialised
// somewhere. For a mysql database, the value for $dbdriver should be
// "mysql".
$dsn = "$dbdriver:host=$dbhost;dbname=$dbname";
$dbh = new PDO($dsn, $dbuser, $dbpassword);
$qry = "SELECT * from err_msgs WHERE id = :e"
$sth = $dbh->prepare($qry);
foreach ($err as $e) {
$sth->bindParam(":e", $e);
$sth->execute();
$row = $sth->fetch();
// Prints out the *second* field of the record
// Note that $row is also an associative array so if we
// have a field called id, we could use $row["id"] to
// get its value
echo "<li><span>".$row[1]."</span></li>";
}
One final point, if you want to simply execute the query once, instead of executing it inside the loop, this is possible but again, may not yield any performance improvement. This could be achieved using the IN syntax. For example, if I'm interested in records with id in the set {5, 7, 21, 4, 76, 9}, I would do:
SELECT * from err_msgs WHERE id IN (5, 7, 21, 4, 76, 9)
I don't think there's a clean way to bind a list using PDO so you would use the loop to build up the string and then execute the query after the loop. Note that a query formulated in this way is unlikely to give you any noticable performance improvment but it really does depend on your specific circumstances and you'll just have to try it out.
You can do this much simpler by doing
$err_csv = implode("','",$err);
$sql = "SELECT FROM err_msgs WHERE id IN ('$err_csv')";
$result = $db -> query($sql);
while ($row = $result -> fetch_array(MYSQLI_BOTH))
{
echo "<li><span>".$row[1]."</span></li>";
}
That way you don't have to keep sending queries to the database.
Links:
http://php.net/manual/en/function.implode.php
I'm unsure whether I should be using mysql_result() or mysql_query() when running a query on a database. Does it make a difference in the case below?
$usertable = 'tableName';
$colName = 'columnA';
$xlookup = 'columnB';
// Connect to Server
$con = mysql_connect($hostname, $username, $password);
// select db
mysql_select_db($dbname);
// run query
$result = mysql_query("SELECT $colName FROM $usertable where $xlookup = 5");
// pass results to webpage
$a = 51;
$x = array($a, $a, mysql_result($result));
echo json_encode($x);
At the moment, whether I use this or not does not make a difference as neither work, but I had thought an error would stop the code from running.
I was trying to use the below code to identify any errors but am not sure if it is correct or not.
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die("<html><script language='JavaScript'>alert('Unable to run query'), $message</script></html>");
}
mysql_query does the query and returns a resultset.
mysql_result returns the rows from that resultset for you to play with.
Look up some examples here.
mysql_result has the distinction of being able to return specific fields, but as other poster noted is slower than the other fetch functions.
mysql_query and mysql_result are two completely different functions which do completely different things.
mysql_query sends an SQL query to the data base.
mysql_result gets a value from a query result according to its row (and optionally a column number, default to zero) number.
That said you should use mysql_fetch_row if you are going to be using more than one datum for each row.
They are different functions. mysql_query executes a query (string) and returns a resource object that you can use to retrieve information from. mysql_result is one of the helper functions that allow you to get that data from the resource. So you'll need both.
Or actually you don't. Once you've used mysql_query, you can use other functions, like mysql_fetch_row too for retrieving data. Most of these functions perform better and more efficient than mysql_result.
HI everyone i tried for 3 days and i'm not able to solve this problem. This is the codes and i have went through it again and again but i found no errors. I tried at a blank page and it worked but when i put it inside the calendar it has the syntax error. Thanks a million for whoever who can assist.
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$testquery = mysql_query("SELECT orgid FROM sub WHERE userid='$userid'");
while($row4 = mysql_fetch_assoc($testquery))
{
$org = $row4['orgid'];
echo "$org<br>";
$test2 = mysql_query("SELECT nameevent FROM event WHERE `userid`=$org AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'") or die(mysql_error());
while($row5=mysql_fetch_assoc($test2))
{
$namethis = $row5['nameevent'];
$calendar.=$namethis;
}
}
First question: what calendar are you talking about?
And here are my 2-cents: does the EXTRACT function returns a string or a number?
Are the "backticks" (userid) really in your query? Try to strip them off.
Bye!
It's a guess, given that you haven't provided the error message you're seeing, but I imagine that userid is a text field and so the value $org in the WHERE clause needs quotes around it. I say this as the commented out testquery has quotes around the userid field, although I appreciate that it works on a different table. Anyway try this:
SELECT nameevent FROM event WHERE userid='$org' AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'
In such cases it's often useful to echo the sql statement and run it using a database client
First step in debugging problems like this, is to print out the acutal statement you are running. I don't know PHP, but can you first build up the SQL and then print it before calling mysql_query()?
EXTRACT() returns a number not a character value, so you don't need the single quotes when comparing EXTRACT(YEAR FROM startdate) = 2010, but I doubt that this would throw an error (unlike in other databases) but there might be a system configuration that does this.
Another thing that looks a bit strange by just looking at the names of your columns/variables: you are first retrieving a column orgid from the user table. But you compare that to the userid column in the event table. Shouldn't you also be using $userid to retrieve from the event table?
Also in the first query you are putting single quotes around $userid while you are not doing that for the userid column in the event table. Is userid a number or a string? Numbers don't need single quotes.
Any of the mysql_* functions can fail. You have to test all the return values and if one of them indicates an error (usually when the function returns false) your script has to handle it somehow.
E.g. in your query
mysql_query("SELECT orgid FROM sub WHERE userid='$userid'")
you mix a parameter into the sql statement. Have you assured that this value (the value of $userid) is secure for this purpose? see http://en.wikipedia.org/wiki/SQL_injection
You can use a JOIN statement two combine your two sql queryies into one.
see also:
http://docs.php.net/mysql_error
http://docs.php.net/mysql_real_escape_string
http://www.w3schools.com/sql/sql_join.asp
Example of rudimentary error handling:
$mysql = mysql_connect('Fill in', 'the correct', 'values here');
if ( !$mysql ) { // some went wrong, error hanlding here
echo 'connection failed. ', mysql_error();
return;
}
$result = mysql_select_db('dbname', $mysql);
if (!$result ) {
echo 'select_db failed. ', mysql_error($mysql);
return;
}
// Is it safe to use $userid as a parmeter within an sql statement?
// see http://docs.php.net/mysql_real_escape_string
$sql = "SELECT orgid FROM sub WHERE userid='$userid'";
$testquery = mysql_query($sql, $mysql);
if (!$testquery ) {
echo 'query failed. ', mysql_error($mysql), "<br />\n";
echo 'query=<pre>', $sql, '</pre>';
return;
}