I need help on my code. When data is entered on my site, it does not show up in the mySQL data table. The insert function that I used might be the problem, but I cannot figure out how to get it to actually insert and show up in my table in my database. Can someone please guide me in the right direction with my code?
<?php
session_start();
include("db_connect.php");
if(isset($_POST['submit'])){
$item = $_POST['item'];
if(empty($item)) {
$errors = "you must enter something";
}
else{
mysqli_query("INSERT INTO a4_todolist (item) VALUES ('$item')");
header('location: index.php');
}
}
$a4_todolist = mysqli_query("SELECT * FROM a4_todolist");
?>
<!DOCTYPE html>
<html>
<head>
<title> Assignment 4 - To Do List </title>
<link rel ="stylesheet" type ="text/css" href="style.css">
</head>
<body>
<div class "head">
<h2> To Do </h2>
</div>
<form method= "POST" action = "index.php">
<?php if (isset($errors)) { ?>
<p><?php echo $errors; ?></p>
<?php } ?>
Item <input type = "text" name= "item" class="item_input">
Author <input type = "text" name= "author" class="author_input">
<button type = "submit" class="add-btn" name="submit"> Add Task
</button>
</form>
<table>
<tbody>
<?php while ($row = mysqli_fetch_array($a4_todolist)) { ?>
<tr>
<td class="id"> <?php print $row['id']; ?> </td>
<td class="item"> <?php echo $row['item']; ?> </td>
</tr>
<?php } ?>
</tbody>
</table>
</thread>
</body>
</html>
You have missed the sql connection variable which is coming from db_connect.php file inside your mysqli_query. Your mysqli_query() should be like this
mysqli_query($connection,"INSERT INTO a4_todolist (item) VALUES ('$item')");
Also this
$a4_todolist = mysqli_query($connection,"SELECT * FROM a4_todolist");
It seems that you are a beginner so I recommend you to learn Prepared statements which is more efficient and safe to use.
You should pass the connection link identifier as well as you can check for errors.
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Also after executing query you can again check for error.
if (!mysqli_query($con,"INSERT INTO a4_todolist (item) VALUES ('$item')")) {
echo("Error description: " . mysqli_error($con));
}
Related
I have this code
<html>
<head>
<meta charset="UTF-8">
<title> Game Library</title>
<link href="css/style.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="wrapper">
<div id="search">
<img id="del" src="img/delete.jpg" alt="Error">
<a class="A" href="index.php"><img class="AR" src="img/src.jpg" title="Search library"></a>
<a class="A" href="insert.php"><img class="AR" src="img/add.png" title="Add game"></a>
<div id="results">
<?php
require("inc/connection.php");
$query = "SELECT * FROM Library";
$result = mysqli_query($conn,$query);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
?><div id="results">
<form action="inc/delete.php" method="GET">
<input type="checkbox" name="checkbox[]" value="<?php echo $row['ID'] ?>">
<p id="p1">Name: <?php echo $row['Name']?>;</p>
<p>Genre: <?php echo $row['Genre']?></p>
<p>Release date: <?php echo $row['Release_date']?></p>
<p>Publisher: <?php echo $row['Publisher']?>:</p>
<p>Platforms: <?php echo $row['Platforms']?></p>
</div>
<?php
}?>
<input type="submit" name = "submit" value = "Submit"></form>
<?php
}else{
echo "No results!";
}
</div>
</div>
</div>
</body>
</html>
And I am supposed to create action="inc/delete.php" script which will allow me to delete multiple rows using checkbox and submit button. Can someone help me out with this please ? I honestly have no clue on how to complete this ....
<?php
if(isset($_POST['submit']))
{
if(!empty($_POST['checkbox']))
{
foreach ($_POST['checkbox'] as $key => $check)
{
// delete query
}
}
}
?>
NOTE: You failed to close PHP at line no. 40. Please make sure your PHP tag is closed or not.
Need to first set form method to `POST'
So, modify
<form action="inc/delete.php" method="GET">
To:
<form action="inc/delete.php" method="post">
And in inc/delete.php,
if (isset($_POST['submit'])){ // Check if form is submitted.
if (! empty($_POST['checkbox'])){ // Check if Checkbox is checked.
// Loop over the checkbox and get selected ids.
foreach($_POST['checkbox'] as $checkbox_id){
echo $checkbox_id."<br/>";
// Add your delete query here.
}
}
}
So the resolution is that you get at your delete script array of ids. You can parse that array and execute DELETE query for each id:
if(isset($_POST['checkbox']))
{
foreach($_POST['checkbox'] as $val)
{
$stmt = $conn->prepare("DELETE FROM Library WHERE id = ?");
$stmt->bind_param('i', $val);
$stmt->execute();
}
}
inc/delete.php
<?php
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['checkbox'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['checkbox'] as $row_id){
echo $row_id."</br>";
// DELETE QUERY HERE
}
}
}
?>
update
Can anyone explain to me why I am getting duplicate messages instead of one?
how can I change my code so that when I type a comment and press "Comment" button, it will only display one message instead of duplicates! When I have one comment boxes it doesn't show duplicate comments, but if I have more than one then it starts duplicating!
COMMENT.INC.PHP
include 'cdbh.inc.php';
function setComments($con)
{
if (isset($_POST['commentSubmit'])) {
$uid = mysqli_real_escape_string($con,$_POST['uid']);
$date = mysqli_real_escape_string($con,$_POST['date']);
$message = mysqli_real_escape_string($con,$_POST['message']);
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid','$date','$message')";
$result = mysqli_query($con,$sql);
}
}
function getComments($con)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($con,$sql);
while ($row=mysqli_fetch_assoc($result)) {
echo $row['uid'];
echo ":";
echo $row['message']."<br><br>";
}
}
page code
<?php
date_default_timezone_set('America/Los_Angeles');
include 'comment.inc.php';
include("connection.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="comment.css" rel ="stylesheet">
</head>
<body>
<?php
$sql="Select * from tbl_images";
$result=mysqli_query($connection,$sql);
while ($row=mysqli_fetch_array($result)) {
?>
<img src="images/<?php echo $row['images_name'] ?>" width="200px" height="200px">
<?php
echo "<form method ='POST' action ='".setComments($con)."'>
<input type ='hidden' name ='uid' value='unknown'>
<input type ='hidden' name ='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'></textarea>
<button type ='submit' name='commentSubmit'>Comment</button>
</form>";
}
getComments($con);
?>
</body>
</html>
Maybe you are submiting all your forms instead of one..
check your database in order to know from what img comes each message.
If you have other code like javascript, you should post it.
I am currently displaying the data using a html table in php from mysql database, and i also i am allowing the user to delete only their own data from the table,my problem is how to match the delete button with the respected row,when user clicks the delete buttons only the specified row should be deleted, but it deletes all the records which is connected to the user in the database, please help me how to do this, PS i am a learner and new to php
UPDATED CODE GOES HERE
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>View cart-d2dn</title>
</head>
<body>
<?php
include('header.php'); ?>
<h1>View Cart</h1>
<table border='1'>
<tr>
<th> VIN </th>
<th> Vehicle Description </th>
<th> Price </th>
</tr>
<?php
session_start();
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT vin,description,price FROM products where user_id='".$_SESSION['use_i']."' ";
$result = mysqli_query($conn, $sql);
$uq=mysql_query("select * from td_user where user_id='".$_SESSION['use_i']."' ");
$u_row=mysql_fetch_array($uq);
if(isset($_REQUEST['delete']))
{
$sql_s =" DELETE FROM `products` WHERE user_id='".$u_row['user_id']."' AND vin='".$_REQUEST['vin']."' " ;
$result_s = mysqli_query($conn,$sql_s) ;
if($result_s == true)
{
echo '<script language="javascript">';
echo 'alert("Deleted successfully")';
echo '</script>';
}
else
{
echo '<script language="javascript">';
echo 'alert("Error in deletion")';
echo '</script>';
}
}
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr>
<td>'.$row['vin'].'</td>
<td>'.$row['description'].'</td>
<td>'.$row['price'].' </td>
<td> <form method="post"> <input type="submit" name="delete" value="Delete">
<input type="hidden" name="vin" value="'.$row['vin'].'">
</form></td>
</tr>';
}
}
else
{
echo "Your cart is empty!";
}
?>
<?php
echo '</table>';
?>
<form><input type="button" value="Go back" onClick="window.location.href='automobile_list.php'">
<input type="button" value="Submit" onClick="window.location.href='mail.php'">
</form>
<?php
mysqli_close($conn);
?>
<?php
include('footer.php');
?>
</body>
</html>
You can do same only if your MySQL table have primary/unique key OR each row is different...
If VIN is unique then Let me show where you need to change. You need to SEND the unique key with delete request to detect which row selected to be deleted. Change the delete button code to:
<form method="post"> <input type="submit" name="delete" value="Delete">
<input type="hidden" name="vin" value="'.$row['vin'].'">
</form>
And in code of deleting row:
if(isset($_REQUEST['delete']))
{
$sql_s =" DELETE FROM `products` WHERE user_id='".$_SESSION['use_i']."' AND vin='".$_REQUEST['vin']."' ";
}
ALSO Delete the mysql code you are using to retrieve user ID (which is just before the code written above). [AND put this delete-code before displaying table(before selecting from product table-look at comments for more info :p )]
If vin is not the primary key then add primary in table by following mathed:
In mysql workbench: right click -> Alter table -> add column ID as INT and check the PK (primary key), AI (auto increment) -> apply -> finish.
Now use ID in place of VIN
As you said you are new to PHP. Then let me give a suggestion:
Use $_POST in place of $_REQUEST coz POST var contains data which sent by POST method only BUT REQUEST contains both POST & GET data... so anybody can delete via just typing in URL as ?delete=delete&vin=3
BTW, its not the issue here, but will help you in future.
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr id="<?php echo $row['id']; ?>" >
<td>'.$row['vin'].'</td>
<td>'.$row['description'].'</td>
<td>'.$row['price'].' </td>
<td> <form method="post"> <input type="submit" name="delete" value="Delete"></form> </td>
</tr>';
$vinrow =$row['vin'] ;
}
}
My aim to is to Update Value in Database By using Update Query . On my first page i have just displayed database table in webpage. Then by using hyperlink i have to click on Edit to second page "edit.php".While on first page i have to get the value of id and send it to second page. Where a input form is displayed which gets Value casually but Id through hidden tag. On third page getting the values query is implented but the value of id is missing.
First Page
<html>
<head>
<title>Assignment</title>
</head>
<body>
<?php
$con=mysql_connect("localhost","root","");
// Check connection
if (!mysql_connect()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$db=mysql_select_db("assignment",$con);
$result = mysql_query("SELECT * FROM teacher ",$con);
?><table cellpadding="2px" border="2px"><?php
while($row = mysql_fetch_array($result)) {
?> <tr>
<td><a href="edit.php?id=<?php
echo $row['id']; ?>">Edit</a > Delete
</td><td>
<?php
echo $row['id']; ?></td><td> <?php echo $row['name'];?></td><td><?php echo $row['program']; ?></td>
<?php }
?></table><?php
mysql_close($con);
?>
</body>
</html>
Secnod Page edit.php
<html>
<head>
<title>Assignment Edit</title>
</head>
<body>
<?php
$id = $_GET['id'];
?>
<form action="update.php" method="get">
Address <input type="text" name="program"><br>
<input type="hidden" name="id" value='<?php $id?>'>
<input type="submit" name="submit">
</form>
</body>
</html>
Third Page update.php
<html>
<head>
<title>Update Page</title>
</head>
<body>
<?php
$add=$_GET['program'];
$id=$_GET['id'];
$con=mysql_connect("localhost","root","");
// Check connection
if (!mysql_connect()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$db=mysql_select_db("assignment",$con);
$query = "UPDATE teacher SET program='$add' WHERE id =".$id;
echo $query;
$result = mysql_query($query,$con);
/* while($row = mysql_fetch_array($result)) {
echo $row['id'] ." " . $row['name']." ". $row['address']."<br>";
}
mysql_close($con);
*/
?>
</body>
</html>
output
UPDATE teacher SET program='openSource' WHERE id =
you need to change this
<input type="hidden" name="id" value='<?php $id?>'>
to
<input type="hidden" name="id" value='<?php echo $id?>'>
(or)
<input type="hidden" name="id" value='<?=$id?>'>
Hello im trying to delete which ever value is selected in a drop down list.
I cant seem to understand what is going on
I have 2 pages 1 with my connection and functions to view the table in a drop down (which works) and a delete function (which doesn't seem to work) and another to call the function in and to delete which ever value is selected.
connection.php
<?php
//Connect to the database
function getSQLConnection() {
$mysqlConnection = new PDO('mysql:host=localhost;dbname=isad235_100000', "root", "");
return $mysqlConnection;
}
//Get all results from members table
function getResults($tablename) {
$sql = "SELECT * FROM " . $tablename;
$mysqlConnection = getSQLConnection();
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
//Delete results from members table
function deleteValue($id) {
$sql = "DELETE FROM members WHERE member_id = '$id'";
$mysqlConnection = getSQLConnection();
$ResultSetting = $mysqlConnection->query($sql);
return $ResultSetting;
}
?>
delete.php
<?php
include_once 'connection.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add</title>
</head>
<body>
<h1> Delete a Member from the Members Table. </h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method='post'>
Delete Member:
<select name='members' value='members'id="Mmembers">
<?php
$results = getResults('members');
if ($results) {
foreach ($results as $row) {
echo '<option value="' . $row['member_id'] . '">' . $row['name'] . '</option>';
}
}
else
echo '<option value="0"0"> No Data</option>';
?>
</select>
<input type="submit" id="delete" value="Delete"/>
<br/>
<br/>
</form>
<?php
if (isset($_POST['members'])) {
$ResultSetting = deleteValue(($_POST['members']));
}
?>
<br/>
<br/>
<form action='index.php' method='GET'>
Go Back:
<input type="submit" name="submit" value="Return"/>
</form>
<br/>
</body>
</html>
I ran your code and don't see any errors with it. Make sure the id column on your 'members' table is called 'member_id'. If there is a discrepancy in the name then the values for the option elements wouldn't be set. Also, the value you just deleted would still appear after the initial page submit. If you reload the page after the submit, you'll see the value has disappeared.