Display single record based from the URL (id) - php

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

Related

mysql query to get a related column

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

How to count the colums in a certain database table + more and show it on website (with php)

I need my visitors on homepage to see how many active user we have. I need to include this with php. (need the code)
in mysql database user is marked with 0 (inactive) and 1 (active).
How can I count/read out the outcome, means all active users, of the database(database_name) - table(user_registration) - colums(each_one) - count(status)?
How to publish this on my website?
Would prefer to this in php cause i'm not so used to js and query.
A simple methode/explanation would be very nice.
Thank you.
(need the code) first this is not a script writing service. Come up with some try and we will try giving a solution.
Basic necessity for your required active user count is to have a status (or name it something) column in your user table.
Then, while a user logs in change the status from 0 to 1 while logs out change it from 1 to 0
by doing so you could easily query it to display the active user.
select column,column from table where status = 1
//(i.e)
select id,userName from users where status = 1
Try using ajax if you want to display it like on-line users displayed in fb
In our implementation, I created a separate DB table active_users, wrote a php function to write user_id and timestamp to this table. This function is called via ajax from your page, bind it to whatever user action you see fit (in our case it is a search).
Write another php function that queries the said tables and retrieves users with time difference between the timestamp and now less than specific value (in our case 5 min). call this function from your page via ajax either in specific time intervals (heartbeat) or user action again - mouse move etc. Display results of this call somewhere (in our case "Active Users" div)
this is what i have.
it works good, but it just shows the amount of lines within.
How can i count all numbers in 'status' within those lines?
<?php
$con = mysql_connect($dbHost, $dbUser, $dbPass );
mysql_select_db($dbName, $con);
$res = mysql_query('SELECT Count(*) FROM ' . 'user_registration', $con);
if ($row = mysql_fetch_array($res, MYSQL_NUM))
{
$users = trim($row[0]);
}
else
{
$users = 'Error';
}
?>
to Show result on website:
<?= $users ?>

Check for duplicate when editing a record in MySQL

I'm having problems with a piece of code and wonder if someone can help.
I have a form that submits information to a MySQL database, I have the correct code for checking to see if the submitted product code already exists, and if so shows a warning message and the record is not added.
That code is:
$result = mysql_query("SELECT * FROM listing_1 WHERE product_code='$product_code'");
$num_rows = mysql_num_rows($result);
if ($num_rows) {
adminwarnmessage("DUPLICATE REFERENCE CODE","FAILURE - <b>$product_name</b> has <b>NOT</b> been added because the reference number already exists.");
}
That works fine for Data Entry, however I have another form that allows users to edit the record, this is what is causing me a problem, as the above code only tells me that there is already a matching record in the database, Of course when I try to save (update) the record it now tells me I can't because it is a duplicate.
What I would like to happen is that it doesn't allow users to choose another productcode that already exists, but I want them to be able to update the record using the same product code the form fetched from the database.
Hope that makes sense, any help greatly appreciated.
If you have id (primary key) then You will have to compare with id of that product before updating the record. For example
$result = mysql_query("SELECT * FROM listing_1 WHERE product_code='$product_code' AND id!=$id");
$num_rows = mysql_num_rows($result);
if ($num_rows) {
echo "duplicate record";
}
Here $id is the id of the product that you should have while editing the record.
following is the step you need to follow when you managing the Database
First you need an primary key(auto_increment) in "ID" field
When you execute insert query that time first check where record is already available or not. if not available than only you should execute insert query.
use primary key filed for update, delete etc...
if you follow the above step than you never face this problem
Are you perhaps checking for duplicate occurrences in both of insert and update statement? If so, you shouldn't. Duplicate entry is relevant only when "inserting". You shouldn't use the same check for update. Hope that helps.
why the same code for update also? you can use another query for updating which is better for debugging if you have problems later. try this
$result = mysql_query("UPDATE listing_1 SET product_code='$new_product_code' WHERE product_code='$product_code' AND id='$id'");
if($result) {
echo "your product was updated.";
} else {
echo "your product is not in DB";
}
EDIT: be careful in updating or inserting things, take always id to check unless your product_code is unique
EDIT
I have resolved this issue by making $productcode field a unique Index.
Now when editing if there is a duplicate..
Mysql does not accept the update query, it returns an error code
I trap that error code and include it in an if statement...
if( mysql_errno() == '1062' )
adminwarnmessage("DUPLICATE REFERENCE CODE","FAILURE - $product_name has NOT been added because the reference number already exists");
}
adminmessage("Item Updated", Congratulations you updated $productname succesfully");
}
This now allows editing of $productcode but does not allow it to be changed to one already used in the database.
Thank you to everyone who took the time to offer help

How get value from POST

This piece of code has been tripping me out for the past four hours. It is deleting a row of photos by the primary ID.
I have var_dump($selectedPhoto) and it is the correct ID, a number. My code will run every time I press delete photo, get to the mysqli_stmt_store_result part and shoots out the $txtMessage, But the database does not update.
This is really weird because I have used the exact same code, with different variables on another page and it works perfectly fine.
Can you see any errors by looking at this? OR have a better way to writing the delete statement.
if (isset($_POST['btnDeletePhoto']))
{
$selectedPhoto = $_SESSION['selectedPhoto'];
$deleteString = "DELETE FROM Photos WHERE PhotoID = ?";
$preparedDeleteStmt = mysqli_prepare($link, $deleteString);
mysqli_stmt_bind_param($preparedDeleteStmt, 'i', $selectedPhoto);
if (!mysqli_stmt_execute($preparedDeleteStmt))
{
mysqli_close($link);
die("The system is not available, try again later");
}
if(mysqli_stmt_store_result($preparedDeleteStmt))
{
$txtMessage = "Delete successfull";
}
To add: $selectedPhoto is a value of a select, drop down list value.
If the photo comes from the value of a select, it is not going to be stored in a session variable, so you probably need to change:
$selectedPhoto = $_SESSION['selectedPhoto'];
to:
$selectedPhoto = $_POST['selectedPhoto'];
Apart from that you need to add error handling to all database operations.

PHP PDO get all row names as objects containing value

I have a mySQL database table setup called site.
Rather than qet the column headings to produce a PHP object of values I want to produce data from the rows.
TABLE: site
:::field:::::value:::::
url www.example.com
name example site
etc Example Etcetera
So I want to be able to get this information from the server by calling the column name I want and the row I am after. I want to do this for all fields in site as I don't want to do multiple calls for the various different rows in site; I'd rather store all the information from the beginning in the object:
eg. <? echo $site['url']; ?>
I created this put it appears to be causing an error:.
$sql = "SELECT * FROM `site`";
$site[];
foreach($sodh->query($sql) as $sitefield){
$site[$sitefield['field']] = $sitefield['value'];
}
Obviously I've missed something. ¿Any idea as to what?
$site[];
should be
$site = array();

Categories