hi i am developing a website and i need to delete files from a server i currently have the following code
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include($_SERVER['DOCUMENT_ROOT'] . "/Scripts/Functions.php");
top();
THis Seems To Be The Problem
$query = "SELECT * FROM 'Gallery' WHERE 'ID' = '20'";
if (!mysqli_query(connect(),$query))
{
die('Error: ' . mysqli_error(connect()));
}
else
{
$Result = mysqli_query(connect(),$query);
while ($row = mysqli_fetch_assoc($Result))
{
$file = get_local($row['Image_Location']);
unlink($file);
$query2 = "DELETE FROM Gallery WHERE ID='20'";
if (mysqli_query(connect(),$query2))
{
header("Location: http://test.co.uk/Gallery/Edit/")
}
else
{
die('Error: ' . mysqli_error(connect()));
}
}
}
bottom();
?>
after going through the code i have worked out that it is an error with the if (!mysqli_query(connect(),$query)) section yet i i cant manage to work out whats wrong.
You appear to be missing a semi-colon on this line:
header("Location: http://www.littlesaintspreschool.co.uk/Gallery/Edit/")
The first problem I spot is that you have your table surrounded by single quotes.
When referring to database elements, like,
the database name
the table name
the field name
You must use backticks ` which is located to the left of the 1 key and above tab.
The second problem I see is that you are passing a function to mysqli_query. Not knowing what the return value is for connect()... I can't exactly say that that is the problem. Regardless, you should store your connection in a variable rather than a function.
Related
I am trying to use the INSERT INTO SQL statement in php. It will input everything correctly up until the last value ($bands_bio). Instead of putting in the correct information, it leaves the value blank. I have looked over everything and can't seem to find any sort of syntax errors.
$page_title = "Create a new band";
require ('includes/database.php');
require_once 'includes/bandsHeader.php';
$band_name = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_name', FILTER_SANITIZE_STRING)));
$band_photo = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_photo', FILTER_SANITIZE_STRING)));
$genre = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'genre', FILTER_SANITIZE_STRING)));
$band_bio = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_bio', FILTER_SANITIZE_STRING)));
echo $band_bio;
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = "")) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/searchFooter.php';
exit;
}
$albums = 0;
$sql = "INSERT INTO bands VALUES (NULL, '$band_name', '$genre', '$albums', '$band_bio')";
$query = #$conn->query($sql);
if (!$query) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/footer.php';
exit;
}
As you can see, I echoed out $band_bio in order to see if it was getting the right value from my form that uses the GET method, which it is so that's not the issue. It has no problem inserting everything correctly up until the last value, which is supposed to be the last column called band_bio in my bands table in my database. It will not output any errors or anything, either. It's almost as if it's taking the string data from the variable and removing all of the text before it inserts the information.
I have been working on this website for a few weeks now and have used the INSERT INTO statement the exact same way on other pages and it works just fine. This is the first thing that has really stumped me and I can't figure it out. Any help is appreciated.
When inserting, ensure that your pk (id) field is set to auto-increment.
This way, you can exert more control over your queries. You should be more successful with:
$sql = "INSERT INTO bands "
. "(`band_name`,`genre`,`numof_albums`,`band_bio`) "
. "VALUES ('$band_name', '$genre', '$albums', '$band_bio')";
By not specifying the pk field, INNODB will automatically increment and insert it for you.
The idea is that you want to specify which columns are being inserted into. Relying on column ordering by mysql is fine, but there may be something at play in your case.
There should be no reason why band_bio would be "left off". You would get a column-mismatch error.
Totally found the answer myself! It, in fact, was a syntax error.
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = ""))
The variable $band_bio was being assigned to a blank string in the if statement since I accidentally used an assignment operator rather than a comparison operator. So the correct code would need to be $band_bio === "" rather than $band_bio = "".
I swear, the problem is always something so much simpler than you think it's going to be.
I am writing a php script which does the following:
Accepts incoming POST data from an article editing page.
Checks if the dropdown list on the previous page was set to "Create New Folder".
If so it checks if something is in the textbox named foldercreate.
Inserts this into the database if it is.
If not it creates a Miscellaneous folder in the database and uses that in the insert.
The trouble is I keep getting a white screen when I hit the form submit button on the previous page. It shows savearticle.php in the address bar but nothing else. It won't even print out error messages. I must have rewritten this about three times now so forgive any logic errors in the code but it should be working as far as I can see. I just want to make sure it's working in its present form before going any further.
The echo statements throughout the code are something I found useful for debugging in the past but it doesn't display a single one.
In the functions.php include I am just using the database connection information as I use this across multiple pages without issue.
Any help would be appreciated as this is getting pretty frustrating.
<?php
echo "start of file";
include_once 'functions.php';
echo "after include";
$title = $_POST[ 'title' ];
$body = $_POST[ 'body' ];
$folderselect = $_POST[ 'folderselect' ];
$foldercreate = $_POST[ 'foldercreate' ];
$newfolderflag = 99;
echo "after variables";
if ($folderselect === "Create New Folder") {
$folder = $foldercreate;
$newfolderflag = 0;
} else if ($foldercreate == NULL && $folderselect === "Create New Folder"){
$folder = "misc";
echo "Nothing selected. Putting in Miscellaneous folder.\n\n";
$newfolderflag = 0;
} else {
$folder = $folderselect;
}
if ($newfolderflag === 0) {
$query = "INSERT INTO folder ('name') VALUES ('$folder');";
if (mysqli_query($db, $query) == TRUE) { echo "New folder created successfully!\n\n"};
}
echo "after if statements";
$query = "SELECT 'folderID' FROM folder WHERE name = $folder;";
$result = mysqli_query($db, $query);
$row = array();
$row = mysqli_fetch_array($result);
$folder = $row['0'];
$query = "INSERT INTO article ( title, body, folderID, userID ) VALUES ('$title', '$body', '$folder', '$user');";
if (mysqli_query($db, $query) === TRUE) {
echo "Article Saved!\r";
echo "Back";
}
echo "after database stuff";
?>
You need to change your select in order to surround $folder with quotes:
$query = "SELECT 'folderID' FROM folder WHERE name = '$folder';";
A while screen means a Fatal error happened in parsing (which almost always means bad syntax, like a missing semicolon). Add the following line to the top of your script and see what the error is.
ini_set('display_errors', 1);
Also, using an IDE that color codes, like NetBeans, can help you tremendously by highlighting syntax issues.
First, error reporting and display should be cranked all the way up in your dev environment. In your php.ini, you should have the following:
error_reporting = -1
display_errors = 1
display_startup_errors = 1
You can recreate those settings in your script for debugging purposes only by adding the following at the top of your current script (must be removed after debugging):
error_reporting(-1);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
Now try again. If you still get nothing, then replace your first debugging echo with a die() statement. I usually use die('wtf?');. If wtf? shows up on the page, then cut and paste it farther down the page. Continue until the white screen reappears and you've found your problem.
Good luck!
I recently converted a code block into a function so I can call it easily more than just once. My problem is that as soon as I related the block to a function it fails the SQL query every time. Here's my code block:
function checkEvent()
{
if(!empty($_GET['e']))
{
$sql = mysqli_query($link, "SELECT * FROM events WHERE EventID = '" . mysqli_real_escape_string($link, $_GET['e']) . "'");
if($sql && mysqli_num_rows($sql)==1)
{
if($row = mysqli_fetch_row($sql))
{
$eventid = $row[0];
$eventname = $row[1];
$desc = $row[2];
$time = $row[3];
echo $_GET['e'];
}
}
else
{
echo $sql;
$failure = "Num Rows Error encountered: " . mysqli_error($link) . " / Num Rows: " . mysqli_num_rows($sqlE);
}
}
}
Now, I've added echos in the relevant places to check and where it currently says echo $sql; if I change that to echo "Fail."; then it will indeed do that. I have tried to get the result as a number of rows and that comes back blank. I don't understand this as my EventID is an AUTO INCREMENT and as such HAD to start at 1. I've triple checked the first entry is 1 as well.
I'm probably not seeing something really obvious, I just can't understand why this code block stopped working the instant I placed a function block around it.
$link doesn't exist inside your function. You either need to pass that as a parameter to the function or skip it entirely and use the "current" DB connection.
"current" in quotes because while it should work just fine while you're utilising a single database connection for the entire process, as soon as you'd start using multiple connections (to connect to multiple databases,) this approach would fail terribly.
good day
need some help here, my Delete button works but page is not automatically refreshing after i clicked the delete button. i still need to manually retrieve the data from db and it would reflect that data is deleted already...
here is my code for delete php: how can i make this to refresh the page automatically?
<?php
require 'include/DB_Open.php';
$id = $_POST['id'];
$idtodelete = "'" . implode("','",$id) . "'";
$query = "DELETE FROM tbl WHERE ticket in (" . $idtodelete . ")";
$myData = mysql_query($query);
echo "DATA DELETED";
if($myData)
{
header("Location: delete.php");
}
include 'include/DB_Close.php';
?>
I suggest fetching the data after your delete logic. Then the delete logic will be executed before fetching the tickets.
Then a redirect to the same page isn't even necessary.
//
// DELETE
//
if (isset($_POST['delete'] && isset($_POST['id'])) {
// Do delete stuff,
// notice delete variable which would be the name of the delete form button e.g.
// If you like, you can still echo "Data deleted here" in e.g. a notification window
}
//
// FETCH data
//
$query = "Select * FROM tbl";
...
if you use post method better with this
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['id'];
$idtodelete = "'" . implode("','",$id) . "'";
$query = "DELETE FROM tbl WHERE ticket in (" . $idtodelete . ")";
if (mysql_query($query))
{
header("Location: delete.php");
} else {
echo "Can not delete";
}
}
As suggested on one of the comments, and on the php documentation:
http://it2.php.net/manual/en/function.header.php :
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
Basically you have to take out the :
echo "DATA DELETED";
What's the point to try to echo that string if the page is going to be redirected anyway?
If you want to make it fancy you could use Ajax to delete it, and trigger a setTimeout() on JavaScript x seconds after showing the message.
Or if you really really really really, REALLY, want to do it this way, you could disable the errors report/display (using error_reporting(0) and ini_set('display_errors', 'Off'). By experience I know that it will work, but it's nasty and extremately ultra highly not recommended
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.