I want to delete some rows from my table. But when I click delete, this just show me a blank page. I'm sure about id value and my db connection.
This is my code:
// connect to the database
include('connect-db.php');
// confirm that the 'id' variable has been set
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// get the 'id' variable from the URL
$id = $_GET['id'];
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM my_table WHERE id = ? LIMIT 1")) {
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: Dashboard.php");
} else {
// if the 'id' variable isn't set, redirect the user
header("Location: Dashboard.php");
}
There is a similar question MySQLi Prepared Statement not executing
. Basically, you can try running the SQL directly in the database to see if you get any errors. Also confirm that the database user has delete permissions and that the id is stored as an integer in your database.
First I'd suggest you use the $_POST method, you can read more about it GET vs. POST.
Try using bindValue() instead of bindParam(), I believe something else needs to be declared for bindParam() I forget (I'm new at PHP too).
Related
I am currently learning PHP Programming,
I wanted to show error when the inputted data exists.
Can anyone show some example on how it doest work?
Here is code I used:
<?php
ob_start();
session_start();
require '../database/database.php';
// require '../database/inc_config2.php';
require ('p_nav.php');
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
// select loggedin users detail
$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
//Variable input data
//include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
// variables for input data
$pcat = $_POST['pcat'];
if($pcat=='')
{
//javascript use for input checking
echo"<script>alert('Please enter Category')</script>";
// echo 'Empty Category';
header ("location:..\product\p_cat.php");
exit();
}
// variables for input data
//check if category is exist
//here query check weather if user already registered so can't register again.
$check_pcat_query="select * from pcategory WHERE pcat='$pcat'";
// $check_user_query="select * from users WHERE user_name='$user_name'";
$run_query=mysqli_query($dbcon,$check_pcat_query);
if(mysqli_num_rows($run_query)>0)
{
//echo "<script>alert('Category $pcat is already exist in our database, Please try another one!')</script>";
exit();
}
// sql query for inserting data into database
//temporary disabled
$sql_query = "INSERT INTO pcategory(pcat) VALUES('$pcat')";
mysql_query($sql_query);
//echo "Supplier Added Successfully";
//header ("location:..\product\index.php");
exit();
/*
$insert_user="insert into pcategory (pcat) VALUE ('$pcat')";
if(mysqli_query($dbcon,$insert_user))
{
// echo"<script>window.open('welcome.php','_self')</script>";
echo "Welcome";
} */
}
// sql query for inserting data into database
?>
There is an error, you are using both MySQL and MySQLi, using both is fatal error if you work on live server. Just focus on MySQLi as MySQL is deprecated officially and is not supported anymore.
Now come to your question. Your logic seems to be fine a bit. This is how you have to implement:
Fetch values from FORM
First clean the input using mysqli_real_escape_string() function.
Use above values and check the record existance in the database (here use SELECT statement)
If mysqli_num_rows() gives you result greater than 0 than;
(a) it means record already exists
(b) else, execute INSERT statement
I am trying to insert $_COOKIE['PHPSESSID'] in db with pdo, but i am having issue, can somebody help out?
here is the db table design : db table name: unregistered_customer_orders
session_id (int)
sel_article_id (varchar, 32)
sel_article_qty(smallint)
sel_article_color(varchar)
sel_article_size(varchar)
order_date(datetime)
HERE IS THE CODE
session_start();
try {
include_once'../includes/connect.inc.php';
$q ="INSERT INTO unregistered_customer_orders SET
session_id = $_COOKIE['PHPSESSID'] ,
sel_article_id = :sel_article_id,
sel_article_qty =:sel_article_qty,
sel_article_color = :sel_article_color,
sel_article_size = :sel_article_size,
order_date = NOW()";
$stm = $pdo->prepare($q);
$stm->bindValue(':sel_article_id', $sel_article_id);
$stm->bindValue(':sel_article_qty', $sel_article_qty);
$stm->bindValue(':sel_article_color', $sel_article_color);
$stm->bindValue(':sel_article_size', $sel_article_size);
$stm->execute();
if ($stm) {
echo "Insert";
exit();
}
else{
echo "Insert failed";
exit();
}
} catch (PDOException $e) {
echo "sth got wrong with the insert".$e->getMessage();
}
Your code has a serious SQL injection problem!
You inject unescaped SQL code into the query - or at least are trying to do so, from the cookie.
The cookie variable should go into the bindValue part just like everything else. Create a new variable name that goes into the prepared statement part, and bind the cookie value to it.
Note that PHP can be configured to use a different name for the session cookie! You don't have to access the $_COOKIE variable after you started the session, you can simply call the session_id() function to get the currently used session id.
Before using session_start(), the configured cookie name can be read by calling session_name(). Don't hardcode the cookie name into your code - it will create hard to debug errors when a new server has a different configuration.
I am using PDO. I want to make a sql statement which gives the user_id of that user which name is in session array. When I get the data from session array in variable and write it in sql it gives nothing but when I write "jhon" it gives user_id that I required. But I want to dynamic sql prepare statement. I see some solution from net but I can't figure it out.
session_start();
if(isset($_SESSION["username"])){
$name=$_SESSION["username"];
function add_posts(){
if($posts_text != ""){
try {
$conn=parent::connect();
$sql1=$conn->prepare("select user_id from user_login
where username=:username ");
$arr=array ('username'=>$name );//when i write "jhon" it gives id 14,
// when i write $name it gives nothing
$sql1->execute($arr);
$fetch = $sql1->fetch();
echo $fetch['user_id'];
}
catch (PDOException $e){
die ("connection failed" .$e->getMessage() );
}
}
}
You need you pass $name argument in your function
function add_posts($name) {
Please help i commented off some stuff for testing purposes but nothing works
<?php
//retrieve the data sent in the POST request
$yourDateOrdered =$_POST["DateOrdered"];
$yourDueDate = $_POST["DueDate"];
if(isset($_POST["CompanyName"])){$yourCompanyName = $_POST["CompanyName"];}
//Validate the fields
if ($yourDateOrdered=="" || $yourDateOrdered==null){
$err= $err."Please enter the date the purchase order was made<br>";
}
if ($yourDueDate=="" || $yourDueDate==null){
$err= $err. "Please enter a date when the item is required<br>";
}
//if ($yourCompanyName=="" || $yourCompanyName==null){
//$err= $err."Please enter the customer name<br>";
//}
//Connect to the server and select database
include("dbConnection.php");
//define sql query to execute on the database
$Query1="INSERT INTO orders(CompanyName, DateOrdered, DueDate)
VALUES ('$yourCompanyName','$yourDateOrdered', '$yourDueDate')";
//execute query
//$result = mysql_query($Query1);
//echo("The following order has been added");
//result of the action stored in $Result
$Result = mysql_query($Query1);
if($Result){
echo 'Order entered';
echo Header ("Location:orderformitem.php");
}
//Close the connection
mysql_close($con);
//Check if query executed successfully and forward the user to an appropriate location
//if($queryResult){
//echo "Order save <br>";
//Header ("Location:../PHP/orderformitem.php");
//}
?>
You definietly need to learn how to debug. First, comment out the Header('Location ...'); row, to catch errors.
add error_reporting(E_ALL); and display_errors(1); at top of your file, to see any errors.
Let's var_dump($_POST) to see, is all the variables are correct.
Do a date validation, if you are want correct dates.
Dump your query, and try to run it in sql directly.
DO NOT use mysql functions because they are deprecated. Use mysqli or PDO instead.
Escape your data, to avoid sql injections!
I have an administration panel that has a page allowing the administrators to delete rows from the database. Each row they can delete has an associated image stored in a directory on the server. The image path is stored in the database as well.
What I need is when a user deletes a row from the table, I would like it to delete the image as well.
Here is my PHP to delete the row from the table:
include('includes/temp.config.php');
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get the 'id' variable from the URL
$id = $_GET['id'];
// delete record from database
if ($stmt = $link->prepare("DELETE FROM templates WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$link->close();
// redirect user after delete is successful
header("Location: edit.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
header("Location: edit.php");
}
But I don't even know where to start to delete the associated image... Any help would be greatly appreciated.
How about the unlink function?
I would ask the user to specify the image, select the image path from the database, delete the image from the file system with the image path I just retrieved and then delete the row from the database.
<?php
require __DIR__ . "/config.php";
if( isset($_GET['id'])){
$id=$_GET['id'];
$res=mysql_query("SELECT image FROM register where id= '$id'");
$row=mysql_fetch_array($res);
$delete="delete from register where id= '$id'";
$de = mysql_query( $delete);
unlink("upload/".$row['image']);
if($de)
{
header("location:login.php");
}
else
{
echo "error";
}
}
?>