Add and edit in one form php - php

I have two files .. addclient.php & Editclient.php.
I want to combine in one php form. can u please help me to do this
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "add";
} else if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "edit"
}
?>
if $id already exist in the table than the row is updated otherwise it's an INSERT.
If you only have an $id : show the form with existing data in it.
If it's not a $id isn't populated : show an empty form.

<?php
if(isset($_GET['id'])) {
$id = intval($_GET['id']);
$stmt = $mysqli->prepare("SELECT id FROM table WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
if($stmt->num_rows > 0) {
// UPDATE
// Text field with the id
echo '<input type="text" name="id" value="'. $id. '"/>';
} else {
// INSERT
// Text field with no id
echo '<input type="text" name="id"/>';
}
}
?>
This validates the integer and makes sure it's one, queries the table for that specific id, if there is more than one row with that id then you need to update, else you need to insert.

<?php
if(isset($_GET['ID'])) {
$ID= $_GET['ID'];
// Use MySQL with $ID to check if the user is existing, and this string will either be 0 or 1
$existing = 0; // 0 = New 1 = Existing
//Add
if($existing== 0) {
}
//Edit
if($existing == 1) {
}
}
?>

Try this
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "update";
}else{
$id = $_GET['id'];
echo "add"
}
?>

Can you try this,
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "Edit";
} else {
echo "Add"
}
?>

try this
if(isset($id) && !empty($id)){
echo "Update";
}else{
echo "Add";
}

Related

How to remove a row from MySQL table data using html delete button in PHP

I am working on a project, for school. I currently have a product page to display an assortment of item includes image, description and price etc...
Under each product I have a delete button, when logged in as admin, which displays fine.
if (is_admin())
echo '<button>Delete item</button>'; }
I want to know how remove the row of data from MySQL table on clicking the delete button.
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
$deleted = mysql_query($db, "DELETE FROM products");
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'$];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo '' . $product_name ."</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo '<button>Delete item</button>';
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
<!-- end snippet -->
You should post to a url with the id in the post data, then redirect back to where you were.
<?php
//html on productpage
if(isset($_GET['product_deleted'])){
if($_GET['product_deleted'] === 'true'){
echo 'The product was deleted';
}else{
echo 'The product could not be deleted';
}
}
if (is_admin()){
/**
* It's a good idea for the page that deletes to be different from the one your on, so that when you redirect back,
* they can refresh the page without getting something
* along the lines of 'refreshing with page will re-post the data'
*/
?>
<form method="POST" action="/product/delete.php">
<button>Delete item</button>
<input type="hidden" name="id" value="<?php echo $image_id; ?>" />
</form>
<?php
}
//PHP on /product/delete.php
if(is_admin() && $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['id'])){
//delete sql here
header('Location: /productpage.php?product_deleted=true'); //redirect back
}
One approach
Change the button to a a element and make the href look like this:
yourdomain.tld/products/delete/{id}
You have to echo the primary key from your mysql database at the id position. It will look like this:
yourdomain.tld/products/delete/5
Then you have to change your .htaccess in a way that all requests go to your index.php in your root project. At the index.php you can do the actually query then.
Update
Keep in mind that anyone visiting this URL can delete products with this approach. You have to make sure that only the admin can do that. The preferred method is a POST request.
You can also send the primary key parameter to your PHP script you are just showed. With this approach you don't need to edit your .htaccess. You may pass it as an URL parameter like this:
yourdomain.tld/your-script.php?delete-product={id}
In your script you can get the parameter like this:
<?php
if (isset($_GET['delete-product'])) {
// your mysql query to delete the product
} else {
// something else
}
If you want to delete the entire row of an record from your db you can do like this. So that you can pass the product id and delete the row. Just bind the id with query using bind parameters concept
$knownStmt=mysqli_prepare($conn, "DELETE FROM `YourTableName` WHERE `pdt_id` = ?;");
if( $knownStmt ) {
mysqli_stmt_bind_param($knownStmt,"d",$pdt_id);
mysqli_stmt_execute($knownStmt);
mysqli_stmt_close($knownStmt);
}

passed variable returns empty in url on target page

I am going out of my mind as it is. I am trying to pass a variable from a page that shows all albums thumbnail image and name to a page that will display all the pictures in that gallery using that passed variable, but the variable is empty in the url on the target page. I have seen similar cases on the web and on this site and I've applied the suggestions but it's still the same. Here is the code that lists the thumbnail and passes the variable(id).
<?php
include ("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
$albums = mysqli_query($conn,"SELECT * FROM albums");
if (mysqli_num_rows($albums) == 0) {
echo "You have no album to display. Please upload an album using the form above to get started. ";
}
else{
echo "Albums created so far:<br><br>";
echo "<table rows = '4'><tr>";
while ($thumb = mysqli_fetch_array($albums)) {
echo '<td><a href ="view.php?id="'.$thumb['id'].'"/><img src = "'.$thumb['thumbnail'].'"/><br>'.$thumb['album_name'].'<br>'.$thumb['id'].'</a></td>';
}
echo "</tr></table>";
}
?>
The code for getting the passed variable is as follows:
<?php
include("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
$db = mysqli_select_db($conn,dbname);
if (isset($_GET['id'])) {
$album_id = $_GET['id'];
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn,$pic);
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
}
else{
echo "Pictures in the gallery:<br><br>";
while ($result = mysqli_fetch_assoc($picQuery)) {
echo "<img src='".$result['photo_path']."'/>";
}
}
}
?>
Please help as i have spent the last two days trying to get it right.
First, your's code is weak against sql injections:
$album_id = $_GET['id']; // here
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
Use either $album_id = intval($_GET['id']) or prepared statements functionality.
Second, add debug lines to your code, like:
<?php
include("config.php");
if (isset($_GET['id'])) {
$album_id = intval($_GET['id']);
var_dump($album_id); // should print actual passed id
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
var_dump($conn _id); // should print conn resource value
$db = mysqli_select_db($conn, dbname);
var_dump($db); // should print 'true' if db select is ok
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn, $pic);
var_dump($picQuery); // should print query resource value
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
} else {
echo "Pictures in the gallery:<br><br>";
while (($result = mysqli_fetch_assoc($picQuery)) !== false) {
var_dump($result ); // should print fetched assoc array
echo "<img src='".$result['photo_path']."'/>";
}
}
}
Notice $album_id = intval($_GET['id']) and while (($result = mysqli_fetch_assoc($picQuery)) !== false) parts
Then follow link view.php?id=<existing-album-id> and observe debug result. On which step debug output differs from expected - there problem is.

Delete confirm only using PHP

I want to delete links to delete images on an SQL database. I am tasked with creating a delete confirm option not using JavaScript just PHP.
require_once("photoalbum-common.php");
$pdo = connect();
if ( isset( $_GET['deletionid'])) {
$errorMessage = deletePhotograph( $pdo, $_GET['deletionid']);
if ( $errorMessage != "") {
print "<div class='errormessage'>$errorMessage</div>\n";
} else {
print "<div class='message'>Image deleted.</div>\n";
}
}
The code below is in "photoalbum-common.php".
<?php
function deletePhotograph( $pdo, $deletionid) {
$errorMessage = "";
// retrieve name of image file so we can delete it
$stmt = $pdo->prepare("SELECT `image` FROM `photographs` WHERE `photoid`=?");
$stmt->execute( array( $deletionid));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ( count( $rows) == 1) {
// delete file
unlink( "images/".$rows[0]['image']);
// delete database record
$stmt = $pdo->prepare("DELETE FROM `photographs` WHERE `photoid`=?");
$stmt->execute( array( $deletionid));
$affected_rows = $stmt->rowCount();
} else if (count( $rows) > 1) {
$errorMessage .= "ID matches more than one record. ";
} else {
$errorMessage .= "ID not found: nothing to delete. ";
}
return $errorMessage;
}
?>
Use something like this. An interstitial page, that accepts a GET request:
GET Request GET /delete.php?id=123
Are you sure you wanna delete?
POST Request POST /delete.php?id=123
Execute the PDO.
You are supposed to write the code for the PHP. If the answer is not enough for this, well, here we go:
<?php
if (count($_POST)) {
// POST Request
deletePhotograph();
} else {
// GET Request
?>
<p>Are you sure you wanna delete?</p>
<!-- Empty action will POST to the same page. -->
<form action="" method="POST"><input type="submit" value="I confirm, Delete" /></form>
<?php
}
?>

Check if row in table is 'equal' to other row

I have the following code to check if a row exists in MySQL:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT 1 FROM files WHERE id='$code' LIMIT 1");
if (mysql_fetch_row($result)) {
echo 'Exists';
} else {
echo 'Does not exist';
}
}
?>
This works fine. But I need to change it a bit. I have the following fields:
id, title, url, type. When someone uses the code above ^ to check if a row exists, I need a variable to get the url from the same row, so I can redirect the user to there.
Do you have any idea how I can do that?
Thanks in advance! :)
Try this:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT * FROM files WHERE id=" . $code . " LIMIT 1");
if (mysql_num_rows($result) > 0) {
while($rows = mysql_fetch_array($result)) {
echo 'Exists';
$url = $rows['url'];
}
} else {
echo 'Does not exist';
}
}
?>
It is quite simple. I think you don't show any effort to find the solution by yourself.
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT url FROM files WHERE id='$code' LIMIT 1");
if ($result) {
$url = mysql_fetch_row($resultado);
} else {
echo 'Does not exist';
}
}
<?php
$sql_query = "SELECT * FROM test WHERE userid ='$userid'";
$result1 =mysql_query($sql_query);
if(mysql_num_rows($result1)>0){
while($post = mysql_fetch_array($result1))
{
$url = $post['url'];
}
}
?>
If mysql_num_rows($result1)>0 it means row is existed fir the given user id

$_GET['id']; if value wrong

I need to print a message if the $_GET[id] is not in database or do this code:
Header('Location:index.php');
Example:
If the people enter in this URL: /index.php?id=100
if there is no page "100" do:
Header('Location:index.php');
Roughly:
<?php
$imageid = (isset($_GET['img_id']) && is_numeric($_GET['img_id'])) ? (int)$_GET['img_id'] : false;
if ($imageid) {
$sql = "SELECT * FROM images WHERE imageid='$imageid';";
$result = mysql_query($sql);
if ($result) {
// imageid exists
my_image_display_function($result);
} else {
// imageid does not exist
header("Location: index.php");
}
}
?>
Update: Edited to more closely match OP's table/variable names.

Categories