Deleting an item from a mysql cart with php - php

I'm creating a cart system and trying to find a way to have a simple button that once pressed deletes the corresponding row. However, I cannot seem to find a way to dynamically do this with while loop I currently have.
<?php
//connect to DB.
$con = mysqli_connect("localhost", "root", "", "books");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySql: ". mysqli_connect_error();
}
$query = "SELECT * FROM cart WHERE customerID = '$_SESSION['id']'";
$result = mysqli_query($con, $query);
//creates a table for dumping the DB to, loops through the DB and posts the contents elegantly.
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td></tr>";
$totalprice += $row['bookPrice'];
}
echo "</table>";
echo "The total present price is: $".$totalprice;
//closes the conncection to the DB
mysqli_close($con);
?>
I've considered trying to put an echo query statement into the database and adding "$row['deletebutton']" to the while loop but I'm not sure that would necessarily work.

The easy way is to create a new page and send the message to this page to delete the item.
So, in the table you add a new column with a link
delete
And in the page you treat this value.

To expand on the comment posted to the question, you could add this to your row:
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td><td><input type='checkbox' name='remove[]' value='" . $row['ROW_ID'] . "' /></td></tr>";
And then with the data submitted in the form you could do something like this:
$query = "DELETE FROM cart WHERE ROW_ID IN (" . implode(',',$_POST['remove']) . ")";
Keep in mind to check the value of remove before using it in queries.

Related

trouble getting info from an array and then inserting it into a db

I have a page that I have been working on. It runs several queries to get existing data from several tables in my DB. There is a table that shows the result of three queries. The first query gets the extension and the secret of phones, the 2nd query gets MAC addresses of phones, and finally the third query gets the names of templates for the phones. The results of the last two queries (with the help of others) are setup as dropdowns in the 3rd and 4th columns of the table created to show the extensions. This way I can select the MAC of the phone I want to assign to the extension and then the template to make the phone work the way I want. The whole page is set as a form and I am using $post to the insert page. My goal here is to take the information (array) that is created by the user making their selections and insert ALL the 4 columns of information into a new table, from there I want to create files using that information to setup the phones. Here is the code I have for now.
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
$link = mysql_connect("localhost", "root", "cacti") or die ('Error connecting to mysql' . mysql_error());
mysql_select_db("cqadmin");
$sql2 = "SELECT extension, secret from extensions;";
$result2 = mysql_query($sql2) or die(mysql_error());
echo "<table border='3'>
<tr>
<th>Extension #</th>
<th>Secret</th>
<th>MAC Address</th>
<th>Template</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
$sql = "SELECT id , mac FROM phones order by mac;";
$result = mysql_query($sql) or die(mysql_error());
$sql1 = "SELECT id , templatename FROM templates order by templatename;";
$result1 = mysql_query($sql1) or die(mysql_error());
echo "<tr>";
echo "<td>" . $row['extension'] . "</td>";
echo "<td>" . $row['secret'] . "</td>";
echo "<td> <select name='phone'>";
while($rowA = mysql_fetch_array($result)) {
echo '<option value="' . $rowA['id'] . '">' . $rowA['mac'] . '</option>';
}
echo "</select></td>";
echo "<td><select name='template'>";
while($rowB = mysql_fetch_array($result1)) {
echo '<option value="' . $rowB['id'] . '">' . $rowB['templatename'] . '</option>';
}
echo "</select></td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" value="Submit your selections">
</body>
</html>
And my insert page
<?php
echo "You got here";
//***********Get the Assignment information *************
$values = array_values($_POST);
print_r($values);
?>
The resulting print shows this
Array ( [0] => 324 [1] => 24 )
Looking at my db table 324 is the index id of the last phone scanned and in the template table 24 is the last template created, No info on the extension or the secret.
I think I am close but I do not know where to go from here.
PS. I know I need to use mysqli or pdo, not sure how to change over yet.

PHP delete functionality probably logical error

In the top of my admin PHP (admin.php), I have loaded data from "Sport" table in "DogSport" MySQL database. After clicking "Edit" link of a particular record, I can
edit, delete that record on "editform2.php". Even on that page, I can also insert a new record.
Problem: Deleting first and second records do not work! Deleting all following records work fine. This problem only with deleting functionality.
Code segment - admin.php
<?php
include("dbconnect.inc.php");
//Retrieving Data
$query1="SELECT * FROM Sport ORDER BY SportId ASC";
$result2=mysqli_query($con, $query1);
$rows=mysqli_num_rows($result2);
$i=0;
if($rows==0)
echo "<br/>There are no records";
else{
echo "<table id='sport'>";
echo "<tr><th>Sport Id</th><th>Sport Name</th><th>Description</th></tr>";
while ($row = mysqli_fetch_array($result2))
{
echo "<tr><td>" . $row["SportId"] . "</td><td>" . $row["SportName"] . "</td><td>" . $row["Description"] .
"</td><td> <a href='editform2.php?id=" . $row["SportId"] . "' target='_blank'>Edit</a></td></tr>";
$i++;
}
echo "</table>";
}
?>
Code segment - editform2.php
if(isset($_POST["delete"])){
include("dbconnect.inc.php");
$query3="DELETE FROM Sport WHERE SportId=$id";
mysqli_query($con, $query3);
echo "<h1>Deleted Successfully</h1>";
mysqli_close($con);
}
I have uploaded necessary files, you can also use to check it including database .sql script. Your help is appreciated.
https://www.dropbox.com/s/wn40u93oa1sxcph/SO.rar?dl=0
$query3="DELETE FROM Sport WHERE SportId=$id";
Where did you set value of $id? It should be $_POST["id"] right?
As a side note - SQL injection risk ...

How to get user information from a MYSQL local database

Hey i need to get information from a database and display it on my index.php.
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('users');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
?>
</body>
</html>
however this will show the information for all of the users in the database.
I have a primary key in the database, which is the account number, could we use this to only display information about that account on the page only?
I will also need to save the details into variables on the php page so some guidance doing that would be greatfull.
Thanks Oliver
In order to retrieve data according to a specific user you must explicitly tell mysql. So, add WHERE id={the I'd u want the info for}.
For your second question. "How do u get the id when the user logs in".
The answer to this is you can (a) how a session initialized at login or (b) how another file or even a loop in the script you need the Id for to run a query for the users name and then you get the Id.
The draw backs of option b is that you are slowing this done and are doing alot of call which can crash your overall site.
The choice is your this is how you can get a particular I'd for a user.
<?php
include('session.php');
?>
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'root', 'Oliver'); //The Blank string is the password
mysql_select_db('users');
$query = "SELECT * FROM username WHERE username='$login_session'"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['username'] . "</td></tr>"; //$row['index'] the index here is a field name
echo "<tr><td>" . $row['sex'] . "</td><td>" . $row['phone'] . "</td></tr>"; //$row['index'] the index here is a field name
echo "<tr><td>" . $row['email'] . "</td><td>" . $row['password'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
?>
</body>
</html>
I got the WHERE username="$login_session"
and the login_session value is a unique value for each of the users in the database so it can never be the same, so i can use this to pull up information for that user only
You can use session variables to store the information in the case you are working with sessions, if not, you can use a regular variable to store the information or maybe use post or get variables

Fill empty cells in table

Basically I have a ranking-page that I'm working on for my CS:GO server. So far it's working fine, and it's looking like this:
https://puu.sh/aJlTj/b6fb5a7a06.png
And the next-page arrow(s) works fine, but the problem is, at page 3+, it's empty because there haven't been more players on the server yet, and it looks like this:
https://puu.sh/aJlXH/7e69071a2b.png
I am using the answer from Make multiple pages out of a mysql query in order to create the pages for all the players.
My table-printing-part looks like this:
echo "<div class='TableGen'><table border='1'><tr><td>Name</td><td>Wins</td><td>Losses</td><td>ELO</td></tr>";
$query = mysqli_query($db, "SELECT * FROM multi1v1_stats ORDER BY wins DESC LIMIT $offset,15");
while($row = mysqli_fetch_array($query)) {
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['wins'] . "</td><td>" . $row['losses'] . "</td><td>" . $row['rating'] . "</td></tr>";
}
?>
</table>
$offset is declared by using $offset = 15 * intval($_GET['page']); unless it's the first page, then it's set to 0.
I understand that this code will only echo out <tr><td></td></tr>'s as long as there's data to post, so how would I go about checking if the page's cells are empty, then just echo out empty cells? (due to this, I can't use empty-cells: show; either as there are no cells to show, not even empty ones)
Thanks in advance.
I think this is what you want... It basically finds the number of rows that were returned and then continues with blanks until the limit is reached.
$limit = 15;
echo "<div class='TableGen'><table border='1'><tr><td>Name</td><td>Wins</td><td>Losses</td><td>ELO</td></tr>";
$query = mysqli_query($db, "SELECT * FROM multi1v1_stats ORDER BY wins DESC LIMIT $offset,$limit");
$i=0;
while($row = mysqli_fetch_array($query)) {
$i = $i+1;
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['wins'] . "</td><td>" . $row['losses'] . "</td><td>" . $row['rating'] . "</td></tr>";
}
for($i=$i;$i<=$limit;$i++)[
echo "<tr><td> </td><td> </td><td> </td><td> </td></tr>";
}
?>
</table>

PHP/MySQL - Unable to INSERT INTO database

I posted a couple days ago and I could not insert an additional record into a MySQL database I setup. I corrected the syntax, but the database will not update again. Basically, I have a couple forms in HTML that carry sessions over to the next pages until the PHP is processes on the final page to INSERT into the database. It worked twice (I have 2 records in the database now), but it won't insert any additional records. It worked fine a couple days ago. The only changes I made to anything was that I added a search feature that accesses the same database with the same user, but the connection is closed at the end of that script as well. Here is the code I am using to INSERT into the database (I know it isn't the best coding job, I'm still learning).
<?php
$con = mysql_connect("localhost","my_username","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dgibbo1_imaging", $con);
// Here too, please mysql_real_escape_string() all parameters
mysql_query("INSERT INTO imaging (os,MAC,Model,AntiVirus,Browser,Email,Connectivity,Sound,Ports) VALUES ('".$_SESSION['imaging2']."','".$_SESSION['imaging3']."','".$_SESSION['imaging4']."','".$_SESSION['antivirus']."','".$_SESSION['browser']."','".$_SESSION['email']."','".$_SESSION['connectivity']."','".$_SESSION['sound']."','".$_SESSION['ports']."')");
OR die("Could not update: ".mysql_error());
mysql_close($con);
?>
The name of the database is imaging. The columns are setup as:
id (This is the primary key field)
os
MAC
Model
AntiVirus
Browser
Email
Connectivity
Sound
Ports
I just find it odd that it inserted records without any problems until I tried it again today. Is it possible that it has something to do with my code for the search?
The search is a simple form on another page and processes this form:
<?php
$con = mysql_connect("localhost","my_user","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dgibbo1_imaging", $con);
// Always escape parameters injected into SQL queries
$result = mysql_query( "SELECT * FROM imaging WHERE MAC LIKE '%"
. mysql_real_escape_string ( $search, $con )
. "%'"
);
echo "<table border='1'>
<tr>
<th>MAC</th>
<th>Model</th>
<th>AntiVirus</th>
<th>Email</th>
<th>Browser</th>
<th>Connectivity</th>
<th>Sound</th>
<th>Ports</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['MAC'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['AntiVirus'] . "</td>";
echo "<td>" . $row['Email'] . "</td>";
echo "<td>" . $row['Browser'] . "</td>";
echo "<td>" . $row['Connectivity'] . "</td>";
echo "<td>" . $row['Sound'] . "</td>";
echo "<td>" . $row['Ports'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Meanwhile, the search will pull up the 2 existing records successfully every time, but I can't add new records and I'm wondering if it has something to do with this.
Thanks for any suggestions. I know my syntax probably isn't the best, so any suggestions from this site are always appreciated.
Try creating a separate php file and hard coding the values into it. Run that and see what happens. your search form shouldnt interfere with another form.
edit any errors when using the form? any errors when inserting to another table?
I saw your post, and it all looks "right". What I'd suggest is to add some logging instead of DIE and look at what MySQL is saying about those insert statements:
$sql = "INSERT INTO imaging ....";
mysql_query($sql);
if(mysql_errno()) {
$message = mysql_error() . "\n" . $sql . "\n";
$fp = fopen('c:\mylogifle.txt', 'a');
fwrite($fp, $message);
fclose($fp);
}
AND...as everyone has mentioned, encode those strings - assuming that the SQL is actually being executed, and you "know" it works, there's a very high possibility that some punctuation in one of the values is interfering with the SQL, like an unexpected comma somewhere that confuses MySQL

Categories