Select, Insert MySQL and PHP - php

I have created a search function and was able to display the rows.
But I have no idea what to do about this thing:
For example, I searched name starting with J, and lists all the names starting with J with login time and has not been logout. Meaning, the timeOut has been set to null from the first place. It displays like:
1 | Johny | 7:58 | (timeOut)
4 | Jess | 8:05 | (timeOut)`
The (timeOut) is a input type="button". And I what I want is whenever I click the logout, for example, I click timeOut for Johny, it will insert values now() for the timeout, not affecting the row for Jess.
I have this code:
<?php
$result=mysqli_query($con,"SELECT * FROM records WHERE PlateNumber LIKE '%$name%'");
while($row = mysqli_fetch_array($result)) {
if($row['TimeOut'] == null){
echo "<table border='1'>" . "<tr>" ."<td style='width:100px;'>" . $row['Number']. "</td>". "<td style='width:100px;'>" . $row['PlateNumber']. "</td>". "<td style='width:100px;'>" . $row['TimeIn'] . "</td>" ."<td style='width:100px;'>" . "<form>" . "<input type='submit' name='logout' value='Log Out'/>" . "</form>". "</td>" . "</table>" ;
if(isset($_POST['logout'])){
//HELP ME IN THIS PART
}
}
}
?>
I'm not really good at php so please bear me with this. Thanks for your help.

I think you meant to update not to insert, and you have to feed the userid to update that particular row.
Also you do not need to spawn every form in the loop. Wrap the table with the form instead.
if(isset($_POST['logout'])) { // if logout button is submitted
// do not insert but update
$id = $con->real_escape_string($_POST['logout']);
$query = $con->query("UPDATE records SET TimeOut = NOW() WHERE id = '$id'");
}
$name = $con->real_escape_string($name);
$result = mysqli_query($con, "SELECT * FROM records WHERE PlateNumber LIKE '%$name%'");
echo '<form method="POST">';
echo '<table boder="1" cellpadding="10">';
while($row = mysqli_fetch_assoc($result)) {
if(empty($row['TimeOut'])){
$id = $row['id'];
echo
"<tr>" .
"<td style='width:100px;'>" . $row['Number']. "</td>".
"<td style='width:100px;'>" . $row['PlateNumber']. "</td>".
"<td style='width:100px;'>" . $row['TimeIn'] . "</td>" .
"<td style='width:100px;'>" .
"<button type='submit' name='logout' value='$id'>Logout</button>" . "</td>" .
"</tr>";
}
}
echo '</table>';

You need to put a record ID of some sort in the 'value' portion of your input. Not just "log out". You need to post "log out jess" (or better yet, just "Jess" so you don't have to edit it when you retrieve it to remove "Log Out" from the string). Usually this is done with a primary key field. But it can also be done with any unique field. So instead of value='Log Out' try value='Jess'.
Then $_POST['logout'] will actually contain Jess and you can build your update sql query from it.
Another method would be to skip the form entirely and just build a web link on the "Log Out" next to "Jess" which would contain "GET" parameters instead of POST. May be easier on the eye.

Instead of a select statement you need to use an update statement and use a where clause to scope the record to the current user based off user id.
So for you it would be like this:
UPDATE records
SET logouttime=now()
WHERE userid='4'

Related

How to pull data from MySQL database with PHP based on DB entry ID

I am complete newbie to PHP/SQL and all this stuff, also not really skilled with any kind of programming. My problem is that I am currently trying to pull out data from MySQL table on to website, but after finishing the code it pulls out all of the data from my table.
I would love to somehow get to pull out only data from specific table row, based on it's primary key. My current code looks like this.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rainbow";
$link = mysqli_connect($servername, $username, $password, $dbname);
if($link === false){
die("ERROR: COuld not connect." . mysqli_connect_error());
}
$sql = "
SELECT name
, nick
, surname
, team
, country
, birthdate
, mouse
, dpi
, keyboard
, headset
FROM players
";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>name</th>";
echo "<th>nick</th>";
echo "<th>surname</th>";
echo "<th>team</th>";
echo "<th>country</th>";
echo "<th>birthdate</th>";
echo "<th>mouse</th>";
echo "<th>dpi</th>";
echo "<th>keyboard</th>";
echo "<th>headset</th>";
echo "</tr>";
while ($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['nick'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['team'] . "</td>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['birthdate'] . "</td>";
echo "<td>" . $row['mouse'] . "</td>";
echo "<td>" . $row['dpi'] . "</td>";
echo "<td>" . $row['keyboard'] . "</td>";
echo "<td>" . $row['headset'] . "</td>";
echo "</tr>";
}
echo "</table";
mysqli_free_result($result);
}
else {
echo "Ziadny vysledok a nic nefunguje";
}
}
mysqli_close($link);
?>
To be honest, I am not even sure if this is the right way to do it, but it works and it pulls the data into a HTML table which is not necessary for me, I just wanted to try it. Thanks for answers!
Let's suppose you have a page with this code:
<form action='page2.php' method='post'>
Inform a number:
<input type='text' name='number'>
<input type='submit' value='Send'>
</form>
Save the form above as page1.php
The file page2.php will contain the code that select one register from your table and show the result.
<?php
$id = $_POST["number"];
//The sql command will look like this:
$sql = "SELECT name, nick, surname, team, country, birthdate, mouse, dpi, keyboard, headset FROM players WHERE id = $id";
?>
A couple of things.
Firstly, You would typically keep some of your confidential stuff (database name, userid, password and server name in a separate file (eg. config.php) and you would "include" that file in this file... include ("config.php");
Secondly, in your $sql line you are selecting all of your columns individually and later in the 10 lines after your "while" statement you are selecting them again (for display). I would be calling the whole table in your $sql line with SELECT * from players and I would follow this with a WHERE. As a newbie, your basic retrive from batabase has 3 main words, SELECT (means go and get what you want and in most cases, grab it all with a *) FROM (the table you want to get it from, in your case the table is players) and WHERE (this is your selection criteria... id > 50...colour = "blue"... whatever you want). When pushing data to the DB you would use SET and UPDATE but when retrieving... SELECT, FROM, WHERE.
Your "while" statement will simply do your $sql statement (select, from, where) and return results until it runs out of records
Good luck Newbie
gri2a

How to select a specific row from a table to edit or delete

I have implemented a booking system, part of the system involves allowing users to modify or delete a booking. I am able to retrieve bookings from the database based on user's session and id which is displayed in a html table. I have been having trouble selecting a specific row from the html table to edit or delete a booking. I want to be able to select a specific row from the html table which i will then be able to edit or delete that record.
The code below retrieves the bookings and displays it in a table
bookings.php
$sqlquery = "SELECT * FROM bookings1,users WHERE bookings1.userid =
users.userid AND users.username = '".$_SESSION['loggedInUser']."' ";
$results = $mysqli->query($sqlquery);
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()){
echo'<form method = "POST" action = "editmot.php" >';
echo'<tr>';
echo "<td>". $row["booking_id"]. "</td>";
echo "<td>". $row["Type"]. "</td>";
echo "<td>". $row["BookingDate"]. "</td>";
echo "<td>". $row["Timeslot"]. "</td>";
echo "<td>". $row["Manufacture"]. "</td>";
echo "<td>". $row["Model"]. "</td>";
echo "<td>". $row["RegistrationNo"]. "</td>";
echo "<td><a href = 'editmot.php' id ='".$row['booking_id']."'> Edit </td>";
echo "<td><a href = 'delete.php' id = '".$row['booking_id']."'> Remove </td>";
echo '</tr>';
echo '</form>';
In the href attribute of the Edit Link, include the Booking_Id as a URL parameter. When the Edit page loads, pick up the booking_id from the URL parameter and fetch the other fields for edit. Like :
echo " <a href = 'editmot.php' . '?EditBookingId=' . $row['booking_id'] "
and then so on and so forth concatenate other things.
Your final href URL should look like :
'http://editmot.php?EditBookingId=24798' or some such.
use this code to edit or delete
for edit
for delete
if(isset($_REQUEST['action']))
if($_REQUEST['action']=="update")
update query
else if($_REQUEST['action']=="delete")
delete query
Instead of using the anchor tag, you could use a submit button and a hidden input field to hold the booking ID, since each booking detail (or row) is in a separate form. You could use something like this in each booking row:
echo "<td><input name='edit' type='submit' value='Edit'>"
. "<input type='hidden' name='booking_id' value='".$row['booking_id']."'></td>";
echo "<td><input name='delete' type='submit' value='Remove'>"
. "<input type='hidden' name='booking_id' value='".$row['booking_id']."'></td>";
And then in editmot.php, process the delete or edit form action:
if (isset($_POST['edit'])) {
// edit video here
}
if (isset($_POST['delete'])) {
// delete video here
}
You need to insert the id in the url so you can get it with the $_GET method in the edit or delete file.
So your anker needs to look something like:
<a href = 'delete.php?id=".$row['booking_id']."'>Delete</a>;
Now when a user go's to that url the url wil look something like:
localhost/delete.php?id=20
Now in your delete.php you can get the id with the $_GET method:
$id = $_GET['id'];
$qry = "DELETE FROM booking1 WHERE id=$id"; //this will delete the row where id is 20

Increase in Value button

I wish to be able to create a button that increase the number of upvotes and decreases the number of downvotes
$result = mysqli_query($con, "SELECT * FROM champion_counters_b WHERE champion_name='" . $search_result . "'");
echo "<table class='champion_counters' border='1'><tr><th>Champion Counter</th><th>Up Votes</th><th>Down Votes</th></tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['champion_counter'] . "</td>";
echo "<td>" . $row['upvotes'] . "</td>";
echo "<td>" . $row['downvotes'] . "</td>";
}
echo "</table>";
As you can see, I am currently echoing a table until there are no search results left for the input. As you can see $row['upvotes'], $row['downvotes'] these are the things that i'd like to be able to generate a button for, on each row.
"Upvote" => upvotes + 1 => 1, 2, 3, etc
"Downvote" => downvotes - 1 => -1, -2, -3, etc
tl;dr: Would like to be able to generate buttons for each row to increase the number of upvotes and decrease the number of downvotes
This might not be what you are looking for, but as far as I understood, this would be my solution:
You will most probably have some kind of primary key in your database. You do actually get it here as you perform a "SELECT *", e.g. retrieve all columns.
Based on the primary key, you can now implement your down- and upvoting functionality. You could for example insert the following into your while-loop (let $row['key'] be the primary key):
echo "<td><a href='action.php?do=up&id=" . $row['key'] . "'>Upvote</a></td>";
echo "<td><a href='action.php?do=down&id=" . $row['key'] . "'>Downvote</a></td>";
Using this, each table row will have two links which will send the user to an action.php and append some GET-Parameters to the URL. The GET-Parameters are "do", which will tell you what to do (either up or down) and "id", which is the primary key.
In action.php, you can read those GET-Parameters and perform any further action, like updating the database. You can get them like this:
$action = $_GET['do'];
$id = $_GET['id'];
Depending on $action, you can now update the downvotes or the upvotes. You can identify the item to update with $id.

Mysql DELETE query strange behaviour

I have populated an html form with MySQL data from a table.
I have included in that table a form, which if submitted, should delete that row of data from the MySQL table.
This is the code that creates populates the table with the MySQL data from my table.(missed out db connection code and other code I have deemed irrelevant).
while($row_data=mysql_fetch_array($table_data)){
echo "<tr>";
echo "<td>" . $row_data['ID'] . "</td>";
echo "<td>" . $row_data['Site'] . "</td>";
echo "<td>" . $row_data['Date'] . "</td>";
echo "<td>" . $row_data['Target_Site'] . "</td>";
echo "<td>" . $row_data['Target_Contact_Email'] . "</td>";
echo "<td>" . $row_data['Target_Contact_Name'] . "</td>";
echo "<td>" . $row_data['Link_Type'] . "</td>";
echo "<td>" . $row_data['Link_Acquired'] . "</td>";
echo "<td>" . $row_data['Notes'] . "</td>";
echo "<td>" . $row_data['Link_URL'] . "</td>";
echo "<td></td>";
echo "<td><form action='delete.php' method='post'><input type='hidden' name='delete_id' value=" . $row_data['ID'] . "><input type='submit' value='✓' name='delete' style='background:none;' /></form></td>";
echo "</tr>";
}
As you can see in that code, there is a table data on the end, which is a form, and if clicked it is meant to delete that given row. As you can see from the form, the action is delete.php.
This is the code for delete.php (missed out db connection code)
$ID = $_POST['delete_id'];
$Delete = $_POST['delete'];
if(isset($Delete)){
mysql_query("DELETE FROM link_building WHERE 'ID'=" . $ID);
header("location:link_building.php?success2=1");
}else{
header("location:link_building.php?fail2=1");
}
Now, it sort of works, but only deletes rows of data that have an ID of 0. Whenever I try to delete a row of data with an ID of 2 for example, it says it succesfully deleted the data, but doesnt actually delete it. But when I click delete on a row with an id of 0 it deletes all the data instead of just that row.
Your issue is that you have quoted 'ID' with single quotes. An integer 0 compared to an any string equates to TRUE in MySQL, and the quoted 'ID' is a string literal rather than a column name, hence your deletion occurs when you pass in the ID=0, but fails in every other circumstance.
Remove the quotes from ID:
mysql_query("DELETE FROM link_building WHERE ID=" . $ID);
//------------------------------------------^^^^
Also, your code is vulnerable to SQL injection. Be sure to properly filter the value of $ID.
if (isset($_POST['delete_id']) && !ctype_digit($_POST['delete_id'])) {
// Non-integer value! error! bail out!
}
else {
$ID = $_POST['delete_id'];
// Do your query...
}
Note that the above code differs from your original in that it checks for the presence of $_POST['delete_id'] and its validity before proceeding with the rest of the operation. In your original, you set the values of $ID and $Delete without checking if they exist. It isn't really necessary to check for $Delete since you only have the one other form input.
A final note: We don't see any authentication code in this post, but be sure that if you are accepting SQL deletions from a form input that you check any permissions on the row being deleted before you delete it. Otherwise, any user could modify the form to delete any other user's rows (if this applies to your situation).

Include different mysql data on a page based on the users choice

I have a problem here I can't solve. I have a database of houses with country, location, price etc entities. I print only the countries in a table using:
while ($data = mysql_fetch_array($select))
where $select is a query that selects specific data from the db. I want to display the full information of the selected db data on a different page i have created. The problem is that i don't know how to take the price of the data the user selected. When i get the price of the $_SESSION['counter'], its the number of the last entity of the db. . I don't want to use javascript etc. Here's the code of the page:
<?php
require_once 'php/core.php'; // opens the database
require_once 'php/openDB.php'; // starts the new session
$select = mysql_query("SELECT ID, Country, City FROM Houses");
$counter = 1;
echo "<form action='house_profile.php' method='get'>
<table width='400'>
<tr>
<td>No.</td>
<td>Country</td>
<td>City</td>";
echo "<tr>";
while ($data = mysql_fetch_array($select))
{
echo "<tr>";
echo "<td>" . $counter . "</td>";
echo "<td>" . $data['Country'] . "</td>";
// echo "<td>" . "<a href='house_profile.php' type='submit' value='$counter'>" . $data['City'] . "</a>" . "</td>";
echo "<td>" . $data['City'] . "</td>";
echo "<td><input type='submit' value='info' name='" . $counter . "'></td>";
echo "</tr>";
$_SESSION['counter'] = $counter;
$counter++;
}
echo "</table>
</form>";
?>`
Clarification:
You can pass any value to house_profile.php by adding a ? to start the querystring, then the name of the variable and the value. If you want to pass the id to house_profile then the link should look like this.
"<a href='house_profile.php?ID=" . $data['ID'] . "'>"
then in house_profile.php update your query like this
$select = mysql_query("SELECT * FROM Houses where ID = " . $_GET['ID']);
Now only the entity they clicked will be available.
FYI $counter is just the count, it's not necessarily the ID of the entity. e.g. if you delete ID 1 your records will start from ID 2 but counter will always start with 1. So to reference your entities correctly use the database ID.
Your query retrieves each house's ID from the database but doesn't display this (unless I don't understand your code). When the user chooses a house, you have to retrieve the ID and then use this in a separate query, such as
select price
from houses
where id = :ID
Currently you're displaying a line counter on your form as opposed to the house's ID - which explains why you write...
When i get the price of the $_SESSION['counter'], its the number of the last entity of the db.
You're passing the value of the row counter to the second query instead of the house's ID.

Categories