Displaying name instead of ID PHP MySQL - php

I need something simple; I have page where a user clicks an author to see the books associated with that author. On my page displaying the list of books for the author, I want a simple HTML title saying: 'The books for: AUTHORNAME'
I can get the page to display author ID but not the name. When the user clicks the link in the previous page of the author, it looks likes this:
<?php echo $row['authorname']?>
And then on the 'viewauthorbooks.php?author_id=23' I have declared this at the start:
$author_id = $_GET['author_id'];
$authorname = $_GET['authorname'];
And finally, 'The books for: AUTHORNAME, where it says AUTHORNAME, I have this:
echo $authorname
(With PHP tags, buts its not letting me put them in!) And this doesnt show anything, however if I change it to author_id, it displays the correct author ID that has been clicked, but its not exactly user friendly!! Can anyone help me out!

You could pull the author_id from the query string as you did using $_GET but beware you will need to validate what is coming through by the query. I hope you can see that without validation how bad of a security hole this is.
I am at work at the moment, but this is a quick example that should give you what you need without sanitizing your query.
$id = intval($_GET['author_id']);
// of course, perform more validation checks
// just don't assume its safe.
$sql = "SELECT authorname FROM authors_tb WHERE author_id=" . $id;
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo "The books for: " . $row['authorname'];
}
The reason why your approach wasn't working was because you utilize the $_GET URL parameter passing for author_name where you weren't supplying the parameters in the URL, just the author_id.

You don't send it in the query string, thus you can't get it from the $_GET array.
Just request it from the database using id.
An important note: Always use htmlspacialchars() when you display the data, coming from the client side.

This is because you do not define the author name in your get.
You should make the following your url:
<?php echo $row['authorname']?>
Or rather select the data from the database again, on the new page, using the ID you retrieved from the URI.

Author name won't be in $_GET. As your code stands, you only use it as the link title. It is no where in the address. Try this instead:
<?php echo $row['authorname']?>
It would be better to re-request it from the database using the author_id though.
EDIT:
To explain the problem in more detail. You have two pages, the new.php page and the viewauthorbooks.php page. You're sending users from the new page to the view page using the link you posted, right?
The problem with that is, your link assigns one variable in get. Here's the query string it would generate:
viewauthorbooks.php?author_id=13
What that will do is send the user to viewauthorbooks and place the value '13' in the $_GET variable: $_GET['author_id']. That is why the author_id is there and displays on viewauthorbooks. However, authorname is never passed to viewauthorbooks, it isn't in $_GET['authorname'] because you never set $_GET['authorname']. If you want it to be in $_GET, then you need your query string to look like this:
viewauthorbooks.php?author_id=13&authorname=bob
You can accomplish that using the new HTML code for the link I posted above. Look at it closely, there's a key difference from the one you have now.
However, it is generally discouraged to pass data through GET, because the query string is displayed to the user and it leaves you open to injection attacks. A better way to do this would be to use the author_id you are already passing to viewauthorbooks.php to retrieve the authorname from the database again. You can use the same code you used on the new.php page.

Related

URL rewriting from id to title

I've got a page with the following url: website.com/foo/bar
Where foo is the page's php file and bar is the corresponding id to be used to pull in the data from the database.
I'm not using any sort of framework trickery. Just an htaccess to remove the .php and extensions and to process the page foo.php with the id as its not in a sub-folder.
Anyways, bar is just a number (like I said corresponds with database row id). For SEO and general readability in a users history I want to go to the more popular website.com/foo/this-is-the-name format (what is this format called??).
Currently my code is:
require('neou_cms/framework/framework.php');
$id = filter(basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
// no id
if (empty($id)) {
header('Location: ../portfolio');
}
$projects = Nemesis::select("*", "projects", "published = '1' AND id = {$id}");
$row_projects = $projects->fetch_assoc();
$totalRows_projects = $projects->num_rows;
// no results, bad id
if ($totalRows_projects <= 0) {
header('Location: ../portfolio');
}
If figure I would do the following (1) make it so that the pages linking to foo instead go to the page title e.g. /this-is-the-name (2) in foo i'd make it so that $id removes the dashes from the name and searches the database for the row using a select statement and the title.
However I feel like this is slow... Is there a better way to do it that wouldn't require me changing the current flow?
Your approach is fine. The this-is-the-name part of your url (website.com/foo/this-is-the-name) is commonly called a "slug". If you'll be querying a database table on the slug, just make sure the slug column has an index and the query should perform reasonably well.
I would also like to point out that you have a SQL injection vulnerability in the code you've posted. Consider binding $id as a parameter in a parameterized query instead of dynamically including it in a where clause.

How to store post variables value

I got a Index page on which search page is included, and when I submit it, it passes values to find.php through action and method post. The code is below
if($_POST['searchsubmit']=="Search"){
$cat=$_POST['searchcategory'];
$area=$_POST['searcharea'];
$term=$_POST['searchbox'];
}
The above code is written on find.php, Now when I try to implement paging through basic paging method with where conditions to make appropiate search query
$where="where approved='yes'";
if($term!=""){
$where.=" and name like '%$term%'";
}
if($cat!=""){
$where.=" and category like '%$cat%'";
}
if($area!=""){
$where.=" and area like '%$area%'";
}
$start=0;
$end=5;
if($_GET['page']!="")
{
$start=$_GET['page']*$end;
}
Where $start is my initial limit, and $end is my number of records. For the first page of paging, I pass a variable page with 0 for first page
First
and my search query now becomes
$que="select * from shops ".$where." ORDER BY likes DESC limit $start,$end";
As soon as I click on "first", My new link become "/find.php?page=0"
and the post values which I recivied from index page search bar are lost.
Is there any way to retain those values ?The two methods which I though are sending them again through url with GET, or the other way is to store them in session.
Is there any third method available ?
Marc is absolutely right. Do not use the code as it is.
As an alternate solution to your problem -
Your page index.php (search form) submits to itself
Assemble your search query as querystring in index.php if its a post
Redirect to find.php with the assembled querystring
Every search information will always be in the querystring.
Use your pagination happily.
The comments are correct.
Use:
// Start the session
session_start();
// Save variables into session
$_SESSION['somevalue'] = $_POST['value'];
Then when any page calls session_start it will have access to $_SESSION['somevalue']
Also, you are wide open for SQL injection. Sanitize your values to ensure no one can put arbitrary sql code into the string. if you are using mysqli it should as simple as this:
// After connecting to the DB
$_POST['somevalue' = $mysqli->real_escape_string($_POST['somevalue']);
Then be sure to hardcode quotes around string values like you are doing.
If you want to be safer you can use prepared statement instead.
Hope this helps.

I want to drop a portion of my url (php variable in the $_GET) when linking to another page

When i click on my table results from an individual sql query.
$zip = mysql_real_escape_string($_GET['zip1']);
$near = "select id, first, last, trainer_address1, CITY, STATE, trainer_zip "
"from event.ACS.trainer where trainer zip ='{$zip}'";
echo lookup_gen::query_results_table($near, matry::base_to('acs/trainer/edit&trainer_id'));
query_results_table just builds the table and rows and allows individual linking for whatever result/row is clicked on.
matry::base_to just Links from the base path.
return A link from the base path to the specified path.
the current page i'm on is:
index.php?q=event/form&id=19471
it has this id variable in the $_GET as shown above.
When i click through on my query_results_table i've set up matry::base_to to link me to
index.php?q=acs/trainer/edit&trainer_id&id=19471
How can i drop the &id=19471 in the end of that url.
Should i use unset or is there a more concise way of going about it, if any at all?
Additionally, if anyone would like me to post the query_results_table function or the matry::base_to function, i'd be more than happy too. Hope I can get this resolved. Thank you.

Insert into sql in PHP

Lets say I have a file called comments.php. In it I have a row like this:
$post_id = $_GET['id'];
$result = mysqli_query($con,"SELECT * FROM comments WHERE post_id = $post_id");
$post_id is the id of the actual entry.
If I echo $post_id it shows the entry's number, no problem there.
There's also a file called comment_send.php.
In it I want to send a comment, alongside with the id of the actual entry, so the comments will know where they belong to.
$post_id = $_GET['id'];
$result = mysqli_query($con,"SELECT * FROM comments WHERE post_id = $post_id");
$sql="INSERT INTO comments (comment, post_id) VALUES ('$_GET[comment]','$post_id')";
However, when I hit the submit button I get this: Notice: Undefined index: id
I dont understand the problem because in the comments.php everything works fine but if I move the same part into another file it fails. Does anyone know what my problem might be?
And yeah, the comment arrives in the database, with the number 0, instead of the entry number.
Your submitting data from the client to the server using a form, right? Check your action on your form. Is it POST (as it should be if you are updating your database)? If so, change $post_id = $_GET['id']; to $post_id = $_POST['id'];
As a troubleshooting tool, I typically add something like echo('<pre>'.print_r($_REQUEST,1).'</pre>'); to the top of my page. You can then find out what type of data you are sending to the server. Then when you get to your SQL statement, be sure to echo the query to see what it is.
Also, sanitize your data as you are open to SQL injection.
It doesn't look like you are passing 'id' to your comment_send.php page. Either pass it in with your comment, or save it as a $_SESSION variable on the previous page.

How to set $userID from queried object ID in Wordpress

I am editing a template to try and add some conditional logic to my page.
The page template shows topics related to a user.
I want to add a piece of code which will grab the user name from the page we are viewing and then use that in a string for my conditional statements.
The code I have put together is as follows, but it breaks my page so I am doing something wrong.
<?php global
// I query the ID and try and set that to the $userID - I think I am doing this wrong, but when I echo the ID it gets the correct info.
$userID = get_queried_object()->ID;
// This is the string I create using the userID which should be from the query above
$memberstatus = get_user_meta($userID,'member_status',true);
?>
later on I use IF statements to use thsi result (which i know work) so i won't post them. My problem is trying to get the above to work.
Any help?
damm, looks like when I remove 'global' from the php it works! I thought global had to be in this...ah well

Categories