I am wondering if there is a possibility.
I have a pagination script that grabs the content from a mysql database with php and using jquery to handle it all.
I want to add a filter to the pagination which will get rid of some content based on the users selection.
When the filter is set I would like the pagination numbers to update to compensate for the items that have been removed.
My biggest concern is that I'm getting the amount of pages to display directly from the database which would make it impossible to update the pagination numbers when filtered:
<?php
include('config.php');
$per_page = 3;
//Calculating no of pages
$sql = "select * from explore";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)
?>
Does anyone know if it is still possible to update these numbers when filtered.
Im mostly using this tutorial in case your wondering:
Here
Just to expand on what Byron said, here is how you do this (based on the code from your link):
Right now in the pagination.php there is a line that looks like this
$sql = "select * from messages";
and in pageination_data.php like this:
$sql = "select * from messages order by msg_id limit $start,$per_page";
Lets say you want a filter that only shows today's messages.
then you would need the following two lines:
$sql = "select * from messages where messages.date = curdate() ";
$sql = "select * from messages where messages.date = curdate() order by msg_id limit $start,$per_page";
of course I expect you will generate the sql statements dynamically in some way. What this allows is the sql server to do the filtering, all the application code stays as you have it.
Note: Remember if you are making dynamic sql to not leave yourself open to sql injection attacks. There are a number of other questions that address sql injection.
The solution is to do the filtration sever side. IE when you apply a filter you send the data to the server and the sql is updated to include/exclude whatever your filter says.
Related
My application has a dashboard screen which has many charts showing metrics and results of user activity, sales performance, etc.
These results can be filtered by date, user and many other options. Supposing I've got one query for each chart, what's the best way to apply the same filtering rule in these multiple queries? Whats the best way to replicate the same "where" clause (the same filtering rule) accross many queries?
As example,
SELECT * FROM users WHERE date = '2014-10-03';
SELECT * FROM products WHERE date = '2014-10-03';
Both queries have same rules.
Some suggested to set a variable with this rule and concatenate it to other queries. Something like:
$where = "WHERE date = '2014-10-03'";
$query = "SELECT * FROM users ". $where;
...
$query = "SELECT * FROM products ". $where;
...
But I can't see this as a good pratice.
If it is similar to issue I had in past I guess you need these restricted by many often repetitive WHERE conditions. User, department permission, time, etc.
What worked in my case was making these into string variables and reusing them across queries that produce charts and graphs. Of course, do not insert user data into your dynamic queries. Hope it helps.
Would it not be a better idea to only keep the value dynamic in case tables do not share the same column name for date.
$date = '2014-10-03';
$query = "SELECT * FROM users WHERE `date_added` = $date";
$query = "SELECT * FROM products WHERE `date_purchased` = $date";
Note: use appropriate validation and security checks for using user input data in sql.
I think you should look into using Prepared Statements. Similar to bind variables in Oracle.
The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters
Good explanation here: http://docs.php.net/pdo.prepared-statements
Prevents SQL injection attacks as well
I've been building my website from the very beginning until today with no framework or WYSIWYG software. I now realize that the way I made it could have been a lot simplier.
I'm a noob in php and mysql and wish to understand how it works. That's why I decided to make a website about a particular theme. That's the best practice to learn these 2 languages...
So,
My website goes about video content with daily updates.
I use to make per video a unique webpage... Now I've more than 300 pages of video content and I want to bring all this content into my database and put it all in one template webpage.
When I want to apply a change, I have to open all those webpages and make on each page the needed changes. Fortunatelly, the search en replace box helps me.
I just wanted to do something on the website that could make my routine and work a lot faster and easier.
I'd like to do some url rewriting with mysql requests.
I'm working on a piece of code, but I can't find what goes wrong with that.
Dreamweaver tells me that there's no error on the synthax, but when I preview it (WAMP) , it keeps showing me an error until a get rid of the 'p' paramater. Hereunder, I join you the code i'm using.
<?php
include "connect.php";
$id = $_GET["id"];
$sql = "SELECT * FROM videos WHERE id=$id LIMIT 1"; //mysql tells me there's a error near LIMIT 1
$req = mysql_query($sql) or die( mysql_error()." ERROR");
$data = mysql_fetch_assoc($req);
if($data["url"]!=$_GET["url"])
{
header("location:/video/atest.php/".$data["id"]."-".$data["url"]); //if the URL is altered, it will be immediatelly fixed thanks to this function
}
?>
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'LIMIT 1' at line 1 ERROR
Thanks to that I will be able to insert on my database every piece of content for each unique video > title, description, ... without the need to make a thousand of changes and upload new webpages.
the URL parameters are also on my database and the php scripts makes the call to the database to retrieve the URL and make this look like a unique webpage.
Oh and sorry for my English...
Thanks a lot.
Try
$id = mysql_real_escape_string($_GET["id"]);
$sql = "SELECT * FROM videos WHERE id=$id LIMIT 1";
try echo $_GET["id"]; before sql and check if you are getting any value. And also learn "PDO" it is better than using direct sql statements or as Joyce said use escape_string.
Change your line:
$sql = "SELECT * FROM videos WHERE id=$id LIMIT 1";
TO THIS:
$sql = "SELECT * FROM videos WHERE id='".$id."' LIMIT 1";
Your SELECT is selecting the string '$id' rather than the php variable $id.
OK, the title may be misleading, I'm a complete novice in MySQL queries via PHP
What im actually trying to do is display a specific title of a row in a link.. for instance:
<?php echo "Link Name"; ?>
url being the row which holds the name of the link eg, link-one. So the finished link would output (if you were to view source):
Link name
My question is how do i select a certain entry in the url row? not just the next/previous/random entry. This may be easy but i cant find an answer. Is this possible?
Will this do the trick?
SELECT url,fn FROM $dbtable WHERE url LIKE '%link-one' ORDER BY order ASC
For this you would do something like:
$sql = "SELECT * FROM table WHERE id='$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo ''.$row["name"].'';
Though php isn't as useful if you don't have a db back end I recommend reading through W3School's sql tutorials, they are quiet good (and free) http://www.w3schools.com/Sql/default.asp
Instead of hard coding sql queries like Select * from users where user_id =220202 can these be made dynamic like Select * from $users where $user_id = $input.
Reason i ask is when changes are needed to table/column names i can just update it in one place and don't have to ask developers to go line by line to find all references to update. It is very time consuming. And I do not like the idea of exposing database stuff in the code.
My major concern is load time. Like with dynamic pages, the database has to fetch the page content, same way if queries are dynamic first system has to lookup the references then execute the queries, so does it impact load times?
I am using codeignitor PHP.
If it is possible then the next question is where to store all the references? In the app, in a file, in the DB, and how?
---EDIT:
Even better: Can the SQL query itself be made dynamic? I can just reference $sqlA instead of the whole query? This way if I have to re-write the query I can just update 1 file.
Because you are using Codeigniter, I would reccomend utilizing the Active Record Class to accomplish what you are trying to do.
The active record class enables you to build queries dynamically in steps allowing you to build them logically. So to take your example using active record...
( this could be accomplished with less code, I'm just trying to illustrate Active Record )
$this->db->select('*');
$this->db->from($table);
$this->db->where($user_id, $input);
and so to show what I mean about building the query logically, you can build whatever logic you want INTO the query building process. Lets say you have a $limit variable that you set if you want to limit the number of results you get. BUT if it isn't set (or NULL) you don't want to set the limit clause.
if ( $isset($limit) ) {
$this->db->limit($limit);
}
and now to execute your query now that it has been built
$query = $this->db->get();
Then just deal with $query with your database class just like you would any other CodeIgniter query object.
Of course you can, if that's what you wish. I'd rather recommend you taking more time to design you database but changes in the schema are inevitable in the long run.
I don't think load time would be an issue with this because ussually the bottleneck in this applications is in the database.
Finally my recommendation is to save this in a file just by declaring the column names as php variables
It depends on the database driver(s) you are using. The old PHP database drivers did not support placeholders (PHP 3.x). The modern (PDO) ones do. You write the SQL with question marks:
SELECT * FROM Users WHERE User_ID = ?
You then provide the value of the user ID when you execute the query.
However, you cannot provide the column name like this - only values. But you could prepare a statement from a string such as:
SELECT * FROM Users WHERE $user_id = ?
Then you provide the value at execute time.
mysql_query() takes a string and it doesn't need to be a constant string, it can be a variable.
$SQL = "SELECT foo FROM bar b";
SQLSet = mysql_query($SQL);
Aa you can see, you can use ordinary string manipulation to build your whole SQL query.
$SQL="SELECT * FROM MyTable";
$BuzID = 5;
$Filter = "Buz=".$BuzID;
if (is_numeric($BuzID)) SQL .= " WHERE ".$Filter;
SQLSet = mysql_query($SQL);
This will expand to "SELECT * FROM MyTable WHERE Buz=5" if $BuzID is set to any number.
If not the statement will just be "SELECT * FROM MyTable"
As you can see, you can build very complex SQL statements on the fly without need of variable support in the SQL server.
IF you want constants such as database name, user login, you can but them in a separate include located outside the public directory.
SecretStuff.inc.php
$__DatabaseName = "localhost";
$__UserName = "DatabaseAccess";
$__Password = "E19A4F72B4AA091C6D2";
Or have the whole PHP database connection code in the same file.
I do have 8 tables. when a query fires from search page data from all these 8 tables is pulled out and displayed on the result page. What I want to know is which is the best optimized query method for this process??
what I do now is :
$result = mysql_query("SELECT * FROM TG_dat,TG_dat1,TG_dat2,TG_dat3 WHERE
TG_dat.web = TG_dat1.web AND TG_dat.web = TG_dat2.web AND TG_dat.web =
TG_dat3.web AND TG_dat.web='".$uri."'")or die(mysql_error());
or do i need to use this??
$result = mysql_query("SELECT * FROM TG_dat WHERE web='$uri'")or die(mysql_error());
$result = mysql_query("SELECT * FROM TG_dat1 WHERE web='$uri'")or die(mysql_error());
$result = mysql_query("SELECT * FROM TG_dat2 WHERE web='$uri'")or die(mysql_error());
$result = mysql_query("SELECT * FROM TG_dat3 WHERE web='$uri'")or die(mysql_error());
Your existing query is perfect - always try to use as few queries as possible.
Less calls to the database is generally better, so you can use the first one.
However, rather than putting all of your tables directly into your FROM clause, it's generally considered good practice to use a join on related tables (which it appears these tables are).
For example:
"SELECT *
FROM TG_dat
LEFT JOIN TG_dat2 USING(web)
LEFT JOIN TG_dat3 USING(web)
WHERE TG_dat.web = '$uri'"
Don't worry so much about the two variations in query you've given - they'll perform more or less the same, but if performance is the issue then the first would be my choice - the single query involves a single round-trip to the server and it's easier to handle the results on the client. It's better to concern yourself with the SELECT *, SELECT <the fields you need> would make more sense - you don't need to have the web field returned multiple times in the results.
your existing query is good. The point is to limit querying db server for better effieciency