mysql query to get a related column - php

hoping you guys can help me with this, im still new to sql and figuring it out.
i have built a page using PHP that $_GET the unique id to display a record.
on this page, i would like to display all the records that share a specific column.
for example
php gets the unique id which is 44.
SELECT * FROM products WHERE id = 44 -- (the problem)
get the data (ie racing) from id = 44 column cat_02
now display all of the product titles that are in cat_02 which are 'racing'
i hope that made sense.

Create a connection to your database
Create a prepared statement with you query
Execute the statement providing you parameter
Loop through the results of the execution
Example:
// creates a new PDO connection, you'll need to modify this to work with whatever DB you are using
$dbh = new PDO('mysql:host='.$host_name.';dbname='.$database, $username, $password);
$stmt = $dbh->prepare("SELECT cat_02 FROM products WHERE id = ?"); // selects just the cat_02 column that has the product titles
if ($stmt->execute(array($_GET['id']))) { // uses the id variable from $_GET
while ($row = $stmt->fetch()) { // loops through all of the rows returned from the query
print_r($row); // do what ever you wanted to with the row of results
}
}

Related

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);

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

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']);
}
}
}

Object of class PDOStatement could not be converted to string

So in my effort to learn PHP I'm trying to make a basic pastebin script.
At the moment I've created a config file and the index.php. I need to echo the text of a table column.
I'm using the following.
$stmt = $connection->prepare("SELECT * FROM paste_docs WHERE option_name = 'content'");
echo $stmt;
But of course that is throwing me an error.
The paste_docs table has two columns.
ID & Content
Side question: how would I get the last valid row ID and add +1 so when a paste submission is made it does not conflict?
add the following
$stmt->execute();
$result = $stmt->fetch(\PDO::FETCH_ASSOC);
See http://php.net/manual/en/pdostatement.execute.php
and http://php.net/manual/en/book.pdo.php

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);
}

add a name value pair to posted data for joomla to consume and insert into DB

I'm trying to use the Joomla framework to make a create in the main content table.[http://docs.joomla.org/How_to_use_the_JTable_class] This works fine except that some data comes from posted variables and some from logic that happens when a file is uploaded moments before (store the random image name of a jpg)
$data=&JRequest::get('post');
this takes a ref to the posted values and I want to add to this Array or Object my field. The code I have makes the new record but the column images, doesnt get my string inserted.
I am trying to do something like$data=&JRequest::get('post');
$newdata=(array)$data;
array_push($newdata,"images"=>"Dog");
i make newdata as data is a ref to the posted variables and i suspect wont there fore allow me to add values to $data.
I'm a flash guy normally not a php and my knowledge is letting me down here.
Thanks for any help
Right, first thing:
$data=&JRequest::get('post');
$data is an array, you do not have to cast it. To add another element to the array as described in the comments do this:
$data['images'] = 'cats';
If you are using normal SQL to do the insert then you would do something like this to get the last inserted id e.g. the id of the row you just inserted:
$db = $this->getDBO();
$query = 'Some sql';
$db->setQuery($query);
if (!$db->query()) {
JError::raiseWarning(100, 'Insert failed - '.$db->getErrorMsg());
}
$id = $db->insertid();
If you are developing in Joomla I suggest you use the db functions provided to you rather than mysql_insert_id();
[EDIT]
If you want to use store then you can get the last inserted id like so:
$row->bind($data);
$row->check();
$row->store();
$lastId = $row->id;

Categories