PHP & MySQL - Get variable on URL - php

I'm a newbie and need Help.
I've made a page (page.php) that shows the list of data from MySQL, but only fetched 6 columns out of the total 10 columns from my table.
Beside each row, I put a link:
<a href="detail.php?id=<?php echo $rows -> num_id;?>" target="_blank">
For example, if a row with num_id=8, the link will be detail.php?id=8, which actually works.
The problem is, how can I set detail.php page to get the num_id?
I have tried using:
if(isset($_GET['id']))
{
$query2="select * from data_table where num_id=$nokasus ";
$result=mysql_query($query2) or die(mysql_error());
while($rows=mysql_fetch_object($result)){ HTML CODE HERE }
Thanks for your help.

how about fetching the id from the url by $_GET[] and assign it to a variable then do your thing.
example:
$id = $_GET['id'];
$query = "SELECT * FROM data_table WHERE num_id = $id" ;

You might be talking about GET[]. Let's also convert your code to MySQLi instead of predicated MySQL.
<?php
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");
$id=mysqli_real_escape_string($con,$_GET['id']);
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
mysqli_query($con,"SELECT * FROM data_table WHERE num_id='$id'");
while($rows=mysqli_fetch_array($result)){ HTML CODE HERE }
?>

Related

How to Link to a page using index number for a dynamic page

I have created a page from the database with the following codes:
<?php
$sql = "SELECT * FROM `inventory` where `prod_id` = 1"; // manipulate id ok
$qry = mysql_query($sql);
$result=mysql_fetch_array($qry);
// this is code to display picture
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['prod_pic'] ).'"/>'
?>
<br>
<?php
// this is to display info
$qry = "SELECT * from inventory where prod_id = 1";
$result = #mysql_query($qry);
while ($row=mysql_fetch_assoc($result)){
echo $row['prod_desc'];
}
?>
Now my problem or question is how do I create a link to replace the id for prod_id, for example sample1 link contains prod_id number 1, how do i make a dynamic page so that when i press sample1 it would go to the page for product number 1 and so on for other links?
I really hope i explained my question well.
I hope that I understand the question but it should work if you replace prod_id = 1 with a parameter.
$qry = "SELECT * from inventory where prod_id = ".$prodID;
Then you create $postID from URL parameters ($_GET / URL Parsing).
exemple with http://yourdomain.com/sample?product=1
$prodID = your_escape_function($_GET['product']);
To avoid some security issues, escape your $prodID variable BEFORE execute your query on database.
Edit : To create your links, you select in your base every products.
$qry = "SELECT * from inventory where prod_id;
Then for each product, you create your URL, (i didn't use mysql_fetch for a while, the code may be wrong, but idea is good) :
$result = #mysql_query($qry);
while ($row=mysql_fetch_assoc($result)){
echo 'Link to product #'.$row['prod_id'].'';
}
(It's really important especially in this case to care about security issues if you put site online/reachable, especially sql injections)
Good luck !

PHP MySQL query result into a variable and then echo ($variable)

wish to check the last id (cat_id) in a table (category) and insert that result into a variable that I can echo.
My intention is to create a record last cat_id +1 as long as it doesnt already exist of course.
What I thought I should do was something like this;
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
echo ($result);
?>
But oh no, nothing so simple. The echo was only to check I had the correct result (in phpmyadmin it returns the desired number)
Then I was hoping to be able to, with a simple html form, was to ask if the user wanted to add a category through a text box:
addrec.html:
<form action="addrec.php" method="post">
Category: <input type="text" name="category">
<input type="submit">
</form>
addrec.php:
<?php
require "mydbdetails.php";
$new_id = $result + 1;
$query="INSERT INTO category VALUES ($new_id, 'Fruits')";
?>
You must first know as a developer, that mysql extension in php will be fully deprecated in the future as it is already in the newer php versions. So use instead Mysqli extension and PDO for sanitation and securer code for your database.
As it goes to your question:- Try the following ;
// Make a MySQL Connection
$query = "SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
//assign result to a variable
$result = mysql_query($query) or die(mysql_error());
//fetch result as an associative array
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['cat_id'];
You can assign it to avariable $row['cat_id'] = $catId; like that and use it .
echo $result[0]['cat_id'] i think
Please consider using PDO query Syntax instead of the old deprecated mysql_query.
If you make a PDO connection and store it in the $conn object ( pretty similar to what you already have in mydbdetails.php) just do:
$query=$conn->query("SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1");
$result=$query->fetchAll(PDO::FETCH_COLUMN,0);
echo ($result[0]);
First of all, you should really be using mysqli instead of mysql because mysql is deprecated and will be removed in PHP 5.5.
Of course the PDO would be better, but i think that you're so new that it would be a bit to much right now.
Basically, you're firing a Query, but you don't tell the query to what connection. You're doing this:
$result=mysql_query($query);
What it should be is
$result=mysqli_query($link, $query);
Where $link is the variable where you're setting up the database connection in the mydbdetails.php file.
Without the connection the Query doesn't know where to get the data from.
But if OOP isn't new to you, the answer from #amenadiel is better because it's an OOP way.
Further, there is no need for your $new_id = $result + 1; line.
IDs should almost always set to Auto Increament in the database, so this line will be done automatically in the database when you're adding a new dataset.
More information here
Hope this helps
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
$i;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
var_dump($row); /* dump rows*/
/* or add to array to use later */
$results[$i] = $row; // add to array
$i++; // +1 the counter to increment the array
}
?>
Try to write your scripts in mysqli_ or pdo functions. Work around in mysql_ function (not recommended)
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$cat_id = $row['cat_id'] + 1;
} else {
$cat_id = 1;
}
?>
cat_is is the primary key? If yes you can set that column as auto increment. You can try this
https://php.net/manual/en/function.mysql-result.php

Using MYSQL to call a row from a table

I am trying to show specific information for my logged in users, i can call the user_name, but i have been able also to call info from the "website" entry which holds the html for the page, i need to be able to call "website" to each logged in user, i.e Susan (user_name) has the html showing when she logs in, BUT Barry (user_name) has the same html showing as susan, as it is being called from Susans row! Please help it is driving me mad!
Here is the code that is on the myaccount.php:
Welcome To <?php echo $_SESSION['user_name'];?>'s Account Page</strong>
<?php
if (isset($_GET['msg'])) {
echo "<div class=\"error\">$_GET[msg]</div>";
}
?>
<?php
$data = mysql_query("SELECT * FROM users") or die(mysql_error());
$info = mysql_fetch_array( $data );
Print "<b></b> ".$info['$website'] . " ";
?>
You have to add a WHERE clause to your query. If you have a field in your table called user_name it will be like this :
"SELECT * FROM users WHERE user_name = '" . $_SESSION['user_name'] . "'";
Note : You are using a deprecated (mysql_query) you should use rather (mysqli_query) which has different syntax
http://php.net/manual/en/mysqli.query.php
Have you tried
$data = mysql_query("SELECT * FROM users WHERE username='$_SESSION[user_name]'") or die(mysql_error());

PHP code to fetch random data from database with link

I have a project from my college. I need to make a site which will generate random data from database. But it will also need to generate a link. So that people can copy that link (as the website is generating different data, people can see the data they want by copying the URL).
I was thinking to use RAND(). But after joining stackoverlow, I see that RAND() is not a good way.
I can fetch random data using RAND() but it is not making any URL. Which is another problem too. I post this problem before. I think I shouldn't use the RAND() function.
this is the code I'm using at this moment:
<!--PHP code for fetching data from database-->
<?php
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xlsx_db", $con);
$result = mysql_query("SELECT * FROM sheet1 ORDER BY RAND() LIMIT 1");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_array($result);
echo "<b>Quote: </b>";
echo $row['quote']."<br>";
echo $row['by']."<br>";
?>
Anyone could please suggest me how to do that? Any kind of help will be very much appreciated.
Not sure if this is actually what you need, but:
<?php
$rand = true;
if (isset($_GET['id'])) {
if (is_int($_GET['id'])) {
$id = (int) $_GET['id'];
$q = 'SELECT * FROM table WHERE id = ?';
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
if (mysqli_stmt_num_rows($stmt) == 1) {
$rand = false;
// display
}
}
}
if ($rand) {
$q = 'SELECT * FROM table ORDER BY RAND() LIMIT 1';
// run query
$res = mysqli_fetch_array($r);
$url = 'www.example.com/index.php?id=' . $res['id'];
}
?>
The prepared statements aren't strictly necessary, since we already make sure that the $_GET['id'] value is an integer, but for the sake of completeness ;D
If you're selecting the data from multiple tables, you could have another table storing the combinations of data and then generate the url using the combination's ID as id parameter.
If you want to get a permalink, you will need to create another page. It will fetch an ID (or something that is identifying the data record you have chosen randomly) and display the specific data. You link to this at your random page.
Find a random row in your database.
Get the row's id.
Concatenate a URL with the id.
The URL should be pointing to a page that would extract the row with the id provided from the table.
I found this the other day and thought it to be pretty comprehensive:
http://mysql.rjweb.org/doc.php/random

sql code not displaying table data

Hello I am trying to understand why this isn't working on my page. I am using the php block below to use the variable I created at the beginning of my page $sel_subj (I used $_GET to get the id of what I clicked on on the previous page. I want the new page to reflect the data of the link I clicked on) I got the url to work to show the correct number from the database but I cannot get my page to display the name of what link was pressed; aka the data in the column labeled 'subject_name' from the 'subjects' table.
<?php
$query = "SELECT * FROM subjects WHERE id = \"$sel_subj\"";
$result_set = mysql_query($query, $connection);
if(!$result_set) {
die("Database query failed: " . mysql_error());
$subject = mysql_fetch_array($result_set);
return $subject;
?>
into this h2 tag right here.
<h2><?php echo $subject['subject_name']; ?>Hello</h2>
I can post the whole page if it will help. I appreciate everyone's input.
Thank you.
edit:new problems
Here is the bottom half of my code. I have a navigation div above this code which separates the links to the pages that relate to the database tables from the content that I'd like to pull from the db and display in the div for the page table.
However with the code I've provided nothing is showing up on the page when I open it in firefox. In my html when I "view source" while previewing on the testing server there is nothing underneath ...
<td id="page">
<?php
$query = "SELECT * FROM subjects WHERE id ='$sel_subj'";
$result_set = mysql_query($query, $connection);
if(!$result_set)
die("Database query failed: " . mysql_error());
$subject = mysql_fetch_assoc($result_set);
return $subject;
?>
<h2><?php echo $subject['subject_name']; ?>Hello</h2>
<br />
<?php echo $sel_page; ?><br />
<?php echo $sel_subj; ?><br />
<?php echo $subject; ?><br />
<?php echo $subject['id']; ?>
</td>
Change this:
$query = "SELECT * FROM subjects WHERE id = \"$sel_subj\"";
to this:
$query = "SELECT * FROM subjects WHERE id = '$sel_subj'";
and this:
$subject = mysql_fetch_array($result_set);
to this:
$subject = mysql_fetch_assoc($result_set);
PS: Try not to use the mysql class of functions anymore, they're not too good. Instead, use mysqli or PDO.
EDIT
If the column id is of numeric type, remove the apostrophes from the query. Like this:
$query = "SELECT * FROM subjects WHERE id = $sel_subj";
Try This
$query = "SELECT * FROM subjects WHERE id = '$sel_subj' ";
Try this
$query = "SELECT * FROM subjects WHERE id = {$sel_subj} ";

Categories