Allow user to select specific row of sql select results? - php

Not sure if this is even possible so sorry if this is a stupid question. I have a sql select query that I will post below. It displays 5 fields into a table from my orders database table. Is there any way that a user can click on one of the rows and then that would take them to a new page showing only that rows results? Is it somehow possible to store the select query results into a session for me to call on the next page? I would like them to be able to print invoices this way. Here is the select sql code.
$sql = "SELECT id, login_id, companyname, address, cost FROM orders WHERE `login_id` = '$_SESSION[login]'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>id</th><th>login_id</th><th>companyname</th>tr><th>address</th><th>cost</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["login_id"]."</td><td>".$row["companyname"]."</td><td>".$row["address"]."</td><td>".$row["cost"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();

Simply save the value of first column (ID). Then use it for new query which selects only this row.

Expanding on i486's answer, here is how you can achieve it in more detail:
Since you already have the $row["id"], you can use this to generate a link:
echo "<a href='newpage.php?id=".$row["id"]."'>Click here</a>";
Now in newpage.php:
// You can access parameters in the url using GET
$id = $_GET["id"];
// Now you can build a new SQL query using this $id, and echo the results table
Do look up the following things:
REST: This explains how GET and POST works
Prepared SQL statements: This will prevent SQL injection, and is needed when you are working with GET or POST values in an SQL query (otherwhise malicious users can destroy your database!)

Related

Is there a way to call a mySQL stored procedure from PHP while passing a $_SESSION variable as its parameter?

What I'm trying to do:
I need to call a stored procedure in PHP, getStudentDevices(), stored on a mySQL server.
It takes one parameter, #p0.
I want to supply that parameter using a $_SESSION variable, studentID.
What works:
I can call the stored procedure from phpMyAdmin and it provides the correct result. So its not an issue with the procedure.
I can query the database from PHP using a different select statement, and I get the results displayed how I want, so I don't think there's an issue with connecting to the DB from PHP.
What I've tried:
This is the PHP used to fetch the results and display them in a table using the same method as mentioned previously:
I have tried using {} to pass the $_SESSION variable too.
<?php
$sql = "CALL getStudentDevices(.$_SESSION["studentID"].)";
$result = mysqli_query($conn, $sql); // $conn details omitted
// If selection is not empty
// Create table row for each record selected
if ($result->num_rows > 0) {
echo "<table> <tr> <th>DeviceID</th> <th>DeviceName</th> </tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr> <td>".$row["DeviceID"]."</td> <td>".$row["DeviceName"]."</td> </tr>";
}
echo "</table>";
} else {
// If select is empty then
echo "0 results";
}
$conn->close();
?>
Here is the stored procedure (which works perfectly when called from the DBMS):
DELIMITER $$
CREATE DEFINER=`username`#`hostname` PROCEDURE `getStudentDevices`(IN `StudentID` VARCHAR(11))
READS SQL DATA
SELECT Devices.DeviceID, Devices.DeviceName FROM Accounts
LEFT JOIN Courses ON Accounts.CourseID = Courses.CourseID
LEFT JOIN Course_Category cc ON Courses.CourseID = cc.CourseID
LEFT JOIN Categories ON cc.Category = Categories.Category
LEFT JOIN Devices ON Categories.Category = Devices.Category
WHERE Accounts.StudentID = #p0 AND Devices.Available = 1$$
DELIMITER ;
The table creation method works when using a select statement ,however, when I try to open this page using the stored procedure, nothing is displayed. The entire page is blank. Please note that security is not a concern.
The problem is how you build your query, you are mixing up the string building styles.
And you are missing quotes for the parameter
The old school style:
$sql = 'CALL getStudentDevices("' . $_SESSION["studentID"] . '")';
Variable passing:
$sql = "CALL getStudentDevices(\"{$_SESSION["studentID"]}\")";

Fetching one row in database

<?php
$stmt = $conn->prepare('SELECT Distinct(specificcategoryname) FROM `clientstable` c,specificcategories s where c.PhoneNumber=:phNo and c.SpecificCategoryId=s.SpecificCategoryId');
$stmt->execute(['phNo'=>$phNo]);
while($row = $stmt->fetch()) {
echo "<tr>";
echo "<td>".$row['specificcategoryname']."</td>";
echo "</tr>";
}
?>
I have code like this need to fetch only one specific value from the database. how can i get the preferred value?
Your, where clause is matching with more than one records that's why more than one records are fetching. if you want to select specific single record then there should be change in sql query. I can't more help because, i need to see the complete schemas of both tables ( clientstable and categorytable) that you are using. Thank you

save pdo query result to variable and use it on other queries

I'm new in php programming, please help me.
I've to make two postgres queries from two separate databases, but one of the fist queries condition based on the other query result:
1st query:
<?php
$result = "SELECT ...
WHERE ... ";
$query = $pgszlaConn->prepare($result);
$query->execute();
while($row = $query->fetch(PDO::FETCH_BOTH)) {
$contractid=$row[0];
echo "<tr><td>$contractid</td></tr>";
?>
/In this query I've multiple results./
2nd query:
<?php
$result = "SELECT ...
WHERE contract.contract_id= :contract";
$query = $pgConn->prepare($result);
$query->bindparam(':contract', $contractid);
$query->execute();
while($row = $query->fetch(PDO::FETCH_BOTH)) {
echo "<tr><td>$row[0]</td></tr>";
?>
My problem is that the 2nd query has only one result based on the 1st query multiple results.
I'm not sure is this a good solution or not but my programming skills not so advanced ;-)
Please help me if you can!
Thanks a lot!
D. Attila
If i understand what you mean.
You need to make the second query within the loop of the first query so that for each id of the first query available, the id will be passed to the second query to query the database of the second table.
Not with my system would have shown you some of my code.
while($row = $query->fetch(PDO::FETCH_BOTH)) {
echo "<tr><td>$contractid</td></tr>";
## now you make the second query to the second table with the id of the first table
$result = "SELECT WHERE contract.contract_id= :contract";
while($row = $query->fetch(PDO::FETCH_BOTH)) {
echo "<tr><td>$row[0]</td></tr>";
} ## end of second query loop
} ## end of first query loop
Something like this should work just get the idea and implement it for yourself

Need to update only one tuple, but this is updating the whole column in table

I check if the the url is present first and see if he is up voting first time, if so then i will add the users repute to the upvoted column, but i want to add only to that url not to all urls, this code is adding to all all tuples in "upvotes" column, i want it to add only to a particular tuple.
<!Doctype html>
<html>
<?php
$c=$_GET['a'];// users name
$d=$_GET['b'];// usesrs id
$e=$_GET['c'];// users repute
$ur=$_POST['url'];
// Create connection
$con=mysqli_connect("localhost","root","","repute system");
if(mysqli_connect_errno()){
echo "ERROR ".mysqli_connect_error();
}
$sql = mysqli_query($con,"SELECT * FROM sites");
if (mysqli_num_rows($sql) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($sql))
{
if($ur == $row['URL'] && $d != $row['id'])
{
$ne = $row['upvotes'] + $e;
$sol = mysqli_query($con, "UPDATE sites SET upvotes = $ne ");
$bew = mysqli_query($con,"INSERT INTO v_sites(teacher_id,URL,vote) VALUES ('$d','$ur','$e')");
echo "Upvoted the site ";
echo $ur;
}
}
} else {
echo "Sorry before upvoting you have to block it first or you are trying to upvote your own report, in which you cant";
}
?>
</html>
You need a WHERE clause that matches the URL:
$stmt = mysqli_prepare($con, "UPDATE sites
SET upvotes = upvotes + 1
WHERE url = ? AND id = ?";
mysqli_stmt_bind_param($stmt, "ss", $ur, $d);
mysqli_stmt_execute($stmt);
You don't need the SELECT or while loop, since MySQL can find the matching rows and update them all by itself.
You also shouldn't have the INSERT query inside the loop, since it's inserting the same row each time.
And you should switch to prepared statements, as shown above, instead of inserting strings into your queries, since your code is subject to SQL injection.
All your rows are being updated because you are not using a where clause.
UPDATE sites SET upvotes = $ne
should be changed to:
UPDATE sites SET upvotes = $ne WHERE id='$d'
However, if $ne is also a string, $ne should also be quoted:
UPDATE sites SET upvotes = '$ne' WHERE id='$d'
Read up on UPDATE:
https://dev.mysql.com/doc/refman/5.0/en/update.html
"My table's name in sites it has 5 columns, which are URL,status,upvotes,downvotes, id and all are varchar with 30 length"
This tells me that id is VARCHAR also; not a good idea but that's up to you. It's best to use int for queries like this should all your id's be numerically-based.
Which is why using quotes WHERE id='$d' around the $d variable will be required.
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.

Select multiple rows of one column

In MySQL, how can I select the data of one column, only for the rows where the value of the same row, in another column, is session_id (I want all the values, not only the first one)
I have tried this:
SELECT column_name FROM table_name WHERE ID = $session_id
...but it dosen't work. It only selects the first row.
edit, the code I'm using.
<?php
$dn = mysql_query("SELECT IDcontact FROM contacts WHERE ID = '".$_SESSION['id']."'");
if(mysql_num_rows($dn)>0)
{
$dnn = mysql_fetch_array($dn);
$req = mysql_query("select TitreEvent, DescriptionEvent, MomentEvent, image_small from users_event where Confidentialite = 'Public' and ID = " . $dnn['IDcontact']);
while($dnn = mysql_fetch_array($req))
{
?>
So it takes for exemple, the value of the contact/friend (IDcontact), form the database «contacts», where the ID of the logged user is. What I want is to output the event of all the IDcontact, cause actually, it only output the event of the most recent friend added, witch is... the first row of the «contacts» database.
The mysql_fetch_array() function returns only one row from the query's result set. If you want to get all the rows produced by the query, you have to call it in a loop:
while ($row = mysql_fetch_array($dn)) {
// Do stuff with $row...
}
Also, this function is deprecated. You should instead be using either mysqli or PDO to run your queries. See the PHP documentation on choosing an API for more information.
Since you edited your question to show that you're running a second query based on the results of the first one, note that you can do both the IDcontact lookup and get the users_event info in a single query by joining the two tables:
select TitreEvent, DescriptionEvent, MomentEvent, image_small
from users_event
join contacts
on contacts.IDcontact = users_event.ID
where contacts.ID = $session_id
Last but not least, anytime you insert variables (such as your session_id) into a database query, you need to be mindful of SQL injection. If the session ID comes from a parameter that the user can control (e.g. a browser cookie), an attacker could send a malicious session ID that contains SQL code to run arbitrary queries in your database. For safety, you should first create a prepared statement that has a placeholder where the parameter should go:
... where contacts.ID = ?
and then plug in the session_id variable afterward as a "bind parameter". Both mysqli and PDO provide ways to do this: mysqli_stmt_bind_param and PDOStatement::bindParam.

Categories