Selecting a specific column in a row associated with a specific id - php

I am running into a little trouble here, I did some searches on Google and Stackexchange to see if someone else had answered this before but it didn't turn up useful content so I am asking for some assistance. I have a column name that does exist in the database however, for some reason the query to MySQL keeps saying that the index by that column name does not exist (Undefined index:) is what I am getting but it is defines in the table so I thought maybe I could go about this another way by requesting the id first, then fetch associated column_name value with that specific id row. Then I want to return that to the variable $column_name to make use of the variable in my next query. Normally when I do $id = $_REQUEST['id']; I get the current id for the item being rendered in the browser. But this "column_name" keeps returning an undefined index error. Yet it exist in the DB just as the ID column does. Why can I call on one and not the other?
How can I call on the specified column_name associated with the id in $_REQUEST['id']; global variable?
In the DB you find:
id = "Value"
itemId = "Item ID"
CategoryName = "Category"
If I request ID 1, how can I fetch the associated CategoryName with that ID?
Thanks for your help!
$id = $_REQUEST['id'];
if(!empty($id)){
$column_name = $this->dbConnection->query("SELECT column_name FROM table //That is directly associated with $id");
}

Add the $id in a WHERE clause in the query:
$column_name = $this->dbConnection->query("SELECT CategoryName FROM table WHERE id = $id");
Also, remember to escape all parameters you send to the databse, without it $id would be vulnerable to SQL Injection attacks.
Good luck :)

I was able to fix this thanks to #frz3993 by adding categoryName={some cat name} to the dynamically generated link redirecting to the page in question while also making the category value dynamically generated as well.
The previous page needed a modification to the link such as
href="DynamicallyGeneratedLink.php?categoryName=%s&id=%s"
This was able to make the category name available for the $_REQUEST[]; variable to then use it to create a new dynamically generated link that would allow the visitors to go back to the previous full list of items in the category without having to use the back button.
Now the following code looks like
function backToCategoryList($dbConnection){
$categoryName = $_REQUEST['categoryName'];
if($r = $this->dbConnection->query("SELECT categoryName FROM table WHERE categoryName = '$categoryName' LIMIT 1")){
while($d = $r->fetch_assoc()){
printf("<i class=\"icon icon-th\"></i>", $d['link'], $d['categoryName']);
}
}
}

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.

Display single record based from the URL (id)

I have a website where it displays all of my records. I can click on an individual record and it gets the student_id of that record and updates it to the URL eg. view_student.php?id=12.
It then takes me to a new page where I want it to display all the information about that record, in this case, show all information about student number 12, but none else.
I haven't a clue how to carry out the statement to display all of the information for that record, this is what I have so far:
if (isset($_GET['student_id'])) {
echo $row['student_name'] . $row['student_age'] . $row['student_gender'];
}
This is a standalone page with nothing else on it. view_student.php simply uses a require function to this script. This code does not display anything, nor does it display any errors. I'm using PDO and I have made sure I'm connected to the database.
My guess is that I will need to use a WHERE clause but I'm just not too sure
Thank you
You can use below PDO query to fetch your data
$statement = $db_con->prepare("select * from student where student_id = :student_id");
$statement->execute(array(':student_id' => $_GET['student_id']));
$row = $statement->fetchAll(PDO::FETCH_ASSOC);

Primary Key of the DB as PHP header info

I have created a registration form which is in application.php and when submitted it is processed and the contents are stored using submit.php and I want to redirect to thanks.php with a parameter called message with value equal to the primay key of the recently inserted row.. For example it should return my 100th applicant to the page,
www.mydomain.com/thanks.php?message=100
where 100 is the Primary key (AI).
In other words I want to print the primary key of the table as a refernce id for the users.. I tried
header("location: thanks.php?message=".$id); and
header("location: thanks.php?message=".$_POST['id']);
Both dont work for me.
Kindly help me guys!
EDIT:
require("admin/sources/connection.php");
$id = mysql_insert_id();
// Other variables are declared here
$sql = "my_INSERT_query_goes_here";
$result = $conn->query($sql);
if($result) {
header("location: thanks.php?message=".$id);
}
This is my submit.php code
Wrong execution order - simple fix
You are first assigning $id, and then running the query.
Twist them around to make it work.
Not using auto-increment?
I see in the query in your comment, that you manually pass the id you want to enter. Did you realize that mysql_insert_id() will not return the sql column that you did call "id", but the column that you set an auto-increment on? That is a single row in your table that automaticly gets an incrementing number without the need to manually enter it.
Couple issues ... it looks like you're mixing mysql_ methods with mysqli and you have the execution in the wrong order.
If your database table is auto-increment, you don't need to pass an ID in the query. By calling $id = mysql_insert_id(); and using the id in the query, you're passing in 0 as the id which uses the next auto-increment id.
Getting the insert_id after $conn->query($sql); will return to you the insert id used.
Echo some variables to see what values you're getting for mysql_insert_id(); before and after.
However, if you're doing a $conn->query(), then you're not using the standard mysql_ functions.
Try this:
require "admin/sources/connection.php";
// Other variables are declared here
$sql = "my_INSERT_query_goes_here";
$result = $conn->query($sql);
if($result) {
$id = $conn->insert_id;
header("location: thanks.php?message=".$id);
}

MySQL won't update if content is changed

I got a PHP and MySQL problem, when I update the headline I got no problem. But when updating while having changed the content it won't update at all.
Any idea to what's going wrong.
$query = mysql_query("UPDATE about SET headline='$headline' WHERE content='$content'")
or die(mysql_error());
$query = mysql_query("SELECT * FROM about ORDER BY id DESC");
while ($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$headline = $row['headline'];
$content = $row['content'];
header("location: ../");
}
I'm coding in PHP and using and MySQL server.
I would prefer a solution that only calls the database once when updating.
When using an UPDATE statement, the WHERE clause is used to specify the record(s) to update. In the following case, where you've modified both the headline and content:
UPDATE about SET headline='$headline' WHERE content='$content'
The above query attempts to update the headline field where the content field equals the new content. There won't be any rows where the existing content matches the new content.
You'd have to do something similar to:
UPDATE about SET headline='$headline', content='$new_content' WHERE content='$old_content'
However, you should generally be selecting a record by an identifier, not a content field.
UPDATE about SET headline='$headline', content='$new_content' WHERE id = $id
If you update using a field like content, you may accidentally update all rows that have the same content, instead of just the row that you're trying to update. Using a unique identifier allows you to update only the specified row.
You could store the identifier in the session (on the server side).

PHP Link Click counter

I want to write simple counter for links/tags. So I have tags and random displayed them to the website
$zmienna = "SELECT name, link FROM tag_content ORDER BY RAND() LIMIT 4";
$result2 = mysql_query($zmienna);
echo $result2;
while($row=mysql_fetch_array($result2)){
echo "<a href='http://www.simplelink.xx/tag/".$row['link']."'>".$row['name']."</a><br>";
}
And now I want to count how many users clicked tags. I created another row named "wys" and tried to write SQL stuff
$wtf = "UPDATE tag_content SET wys=wys+1 WHERE id=2";
$result3=mysql_query($wtf);
As u can see it only works for tag id = 2. And now the problem: how to make it work for all tags?
For example: I have 4 tags with different id. How to make counter "read" the actual clicked tag and make it add "1" to the "wys"?
Thx for help and let me know if u need more information (like code etc.)
As the link field is unique, you can simply use it as an identifier instead of id.
$wtf = "UPDATE tag_content SET wys=wys+1 WHERE link='".$something."";
where $something is a last part of page URL (you should parse it). Of course you also need to check this variable before you use it, because you got it from client side and it could have code for SQL-injection.
You need a way to get the id of all links. Either provide it as a query parameter for the link, or use parse out the name and url from the clicked link and make a relevant SELECT to get the id to loop over.
Use jquery :eq() selector to find out the exact link and then make an ajax request for updating the count

Categories