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.
Related
My site has this about-page with a list of links to click with diffrent classes. These links obviously takes you to diffrent sub-content.
Why do these links have diffrent classes? Because i use javascript and jquery, to grab some content out from a database and smack it in a div on the without reloading... The database has 3 fields: id, headline and content.
The javascript works fine. It does what it should do. it takes the links' class (which is the an ID in the database) and uses it to grab the right content..
Basically:
<?php
//take the post'ed variable you've been given.
if(isset($_POST['id']));
//for convenience use this variable insted
$id = $_POST['id'];
//connect to the database
mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error());
//select database
mysql_select_db("ropox");
mysql_query("SET NAMES utf8");
//Grab this data
$query = mysql_query("SELECT * FROM about WHERE id=$id");
while($row = mysql_fetch_array($query))
{
//echo it bask to the original page. This is printed on the original page
echo $row['content'];
}
?>
When you click the link, it takes 1,03 second before the content appears on the page. At first it was 2 seconds, but I've managed to cut it down. all of my other database connects happens almost instantly and they even echo lots of content through loops. Why is this so slow?
Addressing the SQL Injection aspect:
How can I be vulnerable to SQL injection? There is no way for the user
to input a custom value. I know they could change the ID but what fun
would that be? it would then load nothing...
You're pulling $id directly from the post.
$id = $_POST['id'];
Assuming we have a smart attacker, manipulating the post's data isn't difficult. The SQL Injection attack type that #DanielA.White is warning you of banks on the fact that you're not making sure $id is a number. Because of that, let's pretend that I set the value for id in the post to:
'3; DROP TABLE about;'
Now you're in trouble - the table you were referencing is gone. See http://xkcd.com/327/ for more info. ;)
Sanitizing your input is actually pretty simple - just look here: What's the best method for sanitizing user input with PHP?
write to phpmyadmin the sql: Explain SELECT * FROM about WHERE id=5
if is nagging for id is not indexed, than there you have the problem, easy:)
if you have a loooot of fields in about table, better use field1,field2 instead of *
That is all what can you do for speed up select from sql, others are settings, and hardware, like mysql sever has 1Mb free to run you server and need to do a lot of swapping or your processor is Intel Pentium 1 or 2 something like that...bcause you are connection to localhost, not remote
I am having problems updating and inserting data into my database. I have debugged most of the program so I know for sure that the problem is the line of code for updating and the line of code for inserting data. I am very confused because their are other functions that use the same code and all the variables I used in each function were declared locally in the function so I know they are not conflicting. the code at the top that says
is all the database code to open the line of communication with the database and php. That code works I've already tested it in other programs. I can still pull data with the SELECT code from the database and I've checked and double checked if the names match up with the table. This code is part of some ajax code so it will update in real time but the post I use with the javascript transfers the data just fine to the php file. So I have no idea what I'm doing wrong or if there is just something wrong with the server. If anyone as any ideas please let me know. Also the purpose of this code is to make it so that users can like, favorite, and give a rating out of 5 stars to the content they are viewing on my site.
This is the code:
<?php include "base.php";?>
</head>
<?php
$rateMe = mysql_query("SELECT * FROM rating WHERE Username = '".$_SESSION['Username']."' AND Title = '".$_POST['myTitle']."'");
if(mysql_num_rows($rateMe) == 0)
{
$registerquery = mysql_query("INSERT INTO rating (Username, Author, Star, Like, Favorite, Title) VALUES('".$_SESSION['Username']."','".$_POST['myAuthor']."','".$_POST['myrating']."','".$_POST['myLike']."', '".$_POST['myFavorite']."', '".$_POST['myTitle']."')");
}else
{
$makeUpdate = mysql_query("UPDATE rating SET Star = '".$_POST['myrating']."' WHERE Username = '".$_SESSION['Username']."' AND Title = '".$_POST['myTitle']."'");
}
?>
and this is the table I'm trying to insert data into
table: rating
Username varchar(255)
Author varchar(255)
Star float
Like varchar(255)
Favorite varchar(255)
Title varchar(255)
Here is what your insert query will probably be like when you print it
INSERT INTO rating (Username, Author, Star, Like, Favorite, Title) VALUES('John','Jim','xx','xx', 'xx', 'xx')
The like keyword in the insert statement will probably throw an error like below
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 'like) values('John'
Check your update if it's working
As Markus intimated, your code is extremely vulnerable to SQL injection attacks. Further, the PHP manual strongly recommends using the mysqli extension, over the mysql extension.
I would suggest you take a moment to read through this article on PDO, prepared statements and the right way to INSERT/UPDATE data into your model.
I'm trying to do this IF statement in a mySQL query which I learnt from a YouTube video. I'm not too sure what's going wrong. I do get the following mysql error:
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 'IF(Cuisine != 'Cuisine', WHERE Cuisine='Cuisine') AS ORDER BY
restaurantID' at line 2
Ok, sorry about the lack of detail. Let me explain this a little more.
On my page, I have a HTML form which has 3 drop-downs which act as 'filters'. The default option for one of these 'filters' is Cuisine, which acts as a title, and if it hasn't been changed it means that the user does not want to use the Cuisine as a filter for their search. However if it has changed to say 'Western', then obviously the user wants to use it.
Now, the above problem is quite simple to solve because there is only one filter at a time in place in the above scenario. However, when there are multiple filters being used at once, this is where it gets complicated for me and I don't know how to address this problem.
My solution was to go and search Google for some sort of IF statement in mySQL. I came across this video (which is probably quite good, however since I was very rushed at the time, probably misinterpreted it). Here is the video: http://www.youtube.com/watch?v=3xK5KKQx-J0
I figured that if I could use the condition and try it for the cuisine, I could research and modify it and work on it some more to get it to completely get the filter system to work.
In the code below, my objective is to check what a PHP variable is = to in SQL, and if it's = to 'Cuisine' then I don't want to execute the 'WHERE Cuisine = $cuisine' part of the query. $cuisine is a variable which is taken from a simple HTML/AJAX form dropdown menu using the 'POST' method.
<?php
$result = mysql_query("SELECT * FROM restaurants
IF($cuisine != 'Cuisine', WHERE Cuisine='$cuisine')
ORDER BY restaurantID
")
or die(mysql_error());
?>
P.S I'm not sure if this is the right approach to solving my problem, however I have now described my train of thought and my problem to you above.
I understand your frustration when I left no detail, and once again I apologise, for wasting your time with a poorly written question I will remember to ensure my future questions/answers are more detailed.
I would move the conditional from the SQL query to PHP where the correct query would be built.
if( $cuisine == 'Cuisine' ) ) {
$conditions = '1'; // "WHERE 1" matches every record
}
else {
$conditions = "Cuisine='$cuisine'";
}
$result = mysql_query( "SELECT * FROM restaurants
WHERE $conditions
ORDER BY restaurantID
") or die(mysql_error());
The above assumes that $cuisine is correctly sanitized and escaped.
What are you trying to do? If you want to select all rows where the Cuisine column is not 'Cuisine', use the WHERE clause:
SELECT * FROM restaurants
WHERE Cuisine != 'Cuisine'
ORDER BY restaurantID
Did not fully understand your question, but if you want to select all restaurants by given cuisine and order them by restaurant ID then you can use:
$result = mysql_query("SELECT * FROM restaurants WHERE Cuisine = '$cuisine' ORDER BY restaurantID")
I see multiple problems, which can only be answered if you provide more information. As of now the error in SQL syntax is ,
The syntax of IF condition is
IF(<condition>, <value if true>, <value if false>)
which is troubling you (you have only two parameters for you IF).
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
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.