This piece of code has been tripping me out for the past four hours. It is deleting a row of photos by the primary ID.
I have var_dump($selectedPhoto) and it is the correct ID, a number. My code will run every time I press delete photo, get to the mysqli_stmt_store_result part and shoots out the $txtMessage, But the database does not update.
This is really weird because I have used the exact same code, with different variables on another page and it works perfectly fine.
Can you see any errors by looking at this? OR have a better way to writing the delete statement.
if (isset($_POST['btnDeletePhoto']))
{
$selectedPhoto = $_SESSION['selectedPhoto'];
$deleteString = "DELETE FROM Photos WHERE PhotoID = ?";
$preparedDeleteStmt = mysqli_prepare($link, $deleteString);
mysqli_stmt_bind_param($preparedDeleteStmt, 'i', $selectedPhoto);
if (!mysqli_stmt_execute($preparedDeleteStmt))
{
mysqli_close($link);
die("The system is not available, try again later");
}
if(mysqli_stmt_store_result($preparedDeleteStmt))
{
$txtMessage = "Delete successfull";
}
To add: $selectedPhoto is a value of a select, drop down list value.
If the photo comes from the value of a select, it is not going to be stored in a session variable, so you probably need to change:
$selectedPhoto = $_SESSION['selectedPhoto'];
to:
$selectedPhoto = $_POST['selectedPhoto'];
Apart from that you need to add error handling to all database operations.
Related
I have a website where it displays all of my records. I can click on an individual record and it gets the student_id of that record and updates it to the URL eg. view_student.php?id=12.
It then takes me to a new page where I want it to display all the information about that record, in this case, show all information about student number 12, but none else.
I haven't a clue how to carry out the statement to display all of the information for that record, this is what I have so far:
if (isset($_GET['student_id'])) {
echo $row['student_name'] . $row['student_age'] . $row['student_gender'];
}
This is a standalone page with nothing else on it. view_student.php simply uses a require function to this script. This code does not display anything, nor does it display any errors. I'm using PDO and I have made sure I'm connected to the database.
My guess is that I will need to use a WHERE clause but I'm just not too sure
Thank you
You can use below PDO query to fetch your data
$statement = $db_con->prepare("select * from student where student_id = :student_id");
$statement->execute(array(':student_id' => $_GET['student_id']));
$row = $statement->fetchAll(PDO::FETCH_ASSOC);
I was able to get results before and add into, I am not sure if my SELECT code broke or my INSERT broke, or if my table is not being created anymore.
I just want my table to get populated with new inserts into the db table, better yet inserts to work. Below is my current code for the two main files i'm using. To test I use a FTP to move over my updated files, refresh, and try the buttons. As I said before they worked perfectly fine, up until I created the uninstall function which drops my table.
SOLVED: Whole issue was I made a typo in my table creation code, probably hit backspace by accident.
You need to close the $wpdb->insert();
Try this:
$query = $wpdb->prepare( "insert into {$table_name} (name,category,url) values (%s,%s,%s)",'test,'test','test');
$inserted = $wpdb->query( $query );
if( $inserted ){
echo 'ok';
}else{
echo 'error';
}
instead $wpdb->insert
I am having a php page in which i have captured different values from the previous page, There is also a print button, Which prints all these fields including the unique number. When user clicks on the print button record will be inserted in database and print window displays on the screen. But the problem is there is a unique number on html page, For example if two persons are login at the same time, The will get same unique number, and both will be able to print the same page having same unique number.
How i can control this issue, I also tried to redirect the user to the previous page but its not working.
Here is my php page, Which i am calling using ajax
<?php
$conn = mysql_connect('localhost','','') or die ("");
mysql_select_db("") or die ("Database Problem");
$query = "select * from print where a = $a;
$result = mysql_query($query);
if(mysql_num_rows($result) == 0)
{
$query = "INSERT INTO print () VALUES ()
$result = mysql_query($query) or die();
if(mysql_affected_rows()<>1)
{
header ("Location:mainpage.php?uniquenumber=xy");
}
}
you can use unisid http://php.net/manual/en/function.uniqid.php
To generate an unique id
What is this uniquenumber needed for in the client side? I mean having it accessible and editable for the users is kinda dangerous if it's an important value.
If you just need this number to tell apart the different entries in the print table, why not just use and auto_increment index for this table?
Another solution would be session variables. When a user succesfully logs in generate this unique ID based on multiple variables (username, time, browser), that will ensure there won't be repeated values for this ID. Then store the variable like this:
session_start();
$_SESSION['ID']=$unique_ID;
You can then read it in any other PHP script like this:
session_start();
$unique_ID=$_SESSION['ID'];
You can validate the unique number before inserting to database ( Before Printing also ). If the unique no is exist, throw a error message "unique no is already used " and give another unique number ( By loading the HTML Page again or doing something else ).
Am fairly new to PHP and am making a basic CRUD style management system. I Have an update page and it displays data from a News table, and populates a form with it. The current picture ?(reference) is pulled through and displayed on the form. However if a user wants to change the picture they can press a 'delete' button and then I have written some PHP to display a upload button, set the values in the database for the image to null and hide the delete button, allowing the user to upload a new picture.
The Delete button only removes the reference (path) to the picture from the database, it doesn't delete the actual picture.
This is the HTML control to show the image and delete button. It also shows how the delete button works:
<td align="right">Image 1:</td>
<td align="left"><img src="uploads/newsimages/<?php echo $row["Image"]; ?>" width="230" border="0"> delete</td>
As you can see, when clicked it sets change=imagex and cid= the current news id.
There is then an if statement I have written, but it doesn't seem to only get activated when the delete button is clicked. Because I always get an error that 'cid' is undefined. It is as follows:
<?php
if (isset($_GET['change'] = "image1") {
$query = "UPDATE Table_Name SET Image = '' WHERE NewsID =".$_GET['cid']." ";
}
?>
I am pretty sure my lack of PHP knowledge is letting me down and I am trying to go about this the wrong way, because however I alter the if statement it always gives me an error. First it was cid is undefined so I changed to id but i already use that for something else, another query/function. I hope that all amde sense, can anyone tell me where Im going wrong?
You are missing a parenthesis + you have to specify individually:
if (isset($_GET['change'] = "image1") {
Change to:
if (isset($_GET['change']) && $_GET['change'] == "image1") {
Some more things to consider:
1) Don't use unsanitized values directly from $_GET in a mysql query
WHERE NewsID =".$_GET['cid']."
It is very easy to exploit this with some funky sql injection (see http://xkcd.com/327/ ).
If you are using numeric values for cid, you should cast your $_GET value to integer to prevent sql injection:
$cid = (int)$_GET['cid];
$query = '(...)WHERE NewsID = '.$cid.' limit 1';
Or even better:
$cid = (int)(array_key_exists('cid', $_GET) ? $_GET['cid'] : 0);
if ($cid) {
$query = (...)
}
If you need this kind of sanitizing in different places, you should think about writing a helper function for it to keep your code readable.
2) Don't use GET requests to change data on your server
Imagine a google bot browsing your site and following all those links that you use to delete images. Other scenarios involve users with prefetch plugins for their browsers (e.g. Fasterfox). Also, GET requests may be cached by proxies and browsers, so that the request won't hit the server if you click the link.
The HTTP specification comes with numerous request methods, the most important ones are:
GET to fetch content from the server
PUT to store new information on the server
POST to update existing information on the server
To update your news record (by removing the image) the appropriate method would be POST. To send a POST request, you can use the <form method="POST"> tag.
try this
<?php
if (isset($_GET['change']) && $_GET['change'] == "image1") {
$query = "UPDATE Table_Name SET Image = '' WHERE NewsID =".$_GET['cid']." ";
}
?>
I have a bit of an issue with my code.
I'm making an administrative panel for users to add things to the database. On occasion, they might try to save data without changing it (open a dialog, click save without changing anything). This, of course, will make mysql_affected_rows() return '0' when checking to see if the UPDATE query worked.
Is there another query to make that will always UPDATE regardless of whether the data is the same or not (or can I modify a simple UPDATE query to always update)?
EDIT
This is for users who don't have programming experience. Of course you wouldn't want to update if there's no reason to, but when a user tries to update and it doesn't happen I end up showing a failure message. Rather than there being something wrong, its just it doesn't need to be updated. I need a way to show the user that, instead of a generic 'failure' message. If it failed for another reason, I still need to know.
From the MySQL Documentation:
If you set a column to the value it currently has, MySQL notices this
and does not update it.
Instead of checking mysql_affected_rows, just check to see if the query was successful:
if(!mysql_query("UPDATE ..."))
{
//failure
}
else
{
$verification = mysql_query("SELECT ROW_COUNT() as rows_affected");
$row = mysql_fetch_row($verification);
$rows_affected = $row[0];
if ($rows_affected > 0)
{
//update was performed
}
else
{
//no update was needed
}
}