I currently have a database with a table called rooms; which has two attributes: roomID and roomType. I have inserted data into this using MySql which is all fine. I am using PHP and MYSQL in order to show what's currently in the database on the page (which is working just fine) and then a delete.php page where I have a text field for Room ID and Room Type. I wish to delete whatever I prefer from the 'rooms' table however I keep getting the Unknown table 'roomid' in MULTI DELETE error, even though I only have the one table.
Below is my current PHP
<?php
include ('connect.php');
if(isset($_POST['roomID'])){
$roomID = $_POST['roomID'];
$roomType = $_POST['roomType'];
$sql = "DELETE FROM rooms WHERE roomID='"$roomID"' AND roomType='"$roomType"' ";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
Would appreciate any help
WARNING!
Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe!
Here's the problem -
If only you had used prepared statements you wouldn't have had to worry about concatenating the variables properly. The following portion of your query line is missing the proper concatenation:
WHERE roomID='"$roomID"' AND roomType='"$roomType"'
Related
I have a PHP script that reads a database table and inserts all the rows into an HTML table until it's displayed all available rows as shown here:
require_once('dbconnect.php');
$sql =
"SELECT
ID, Site, Type, Requested, Quote,
PO, CADs, MCS, DFP,
SIM, Prereqs, Design, Report, Delivered
FROM Predictions";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<table class="table table-hover table-condensed">';
while($row = $result->fetch_assoc()) {
echo
'<tbody>'.
'<tr>'.
'<td>'.$row['ID'].'</td>'.
'<td>'.$row['Site'].'</td>'.
'<td>'.$row['Type'].'</td>'.
'<td>'.$row['Requested'].'</td>'.
'<td>'.$row['Quote'].'</td>'.
'<td>'.$row['PO'].'</td>'.
'<td>'.$row['CADs'].'</td>'.
'<td>'.$row['MCS'].'</td>'.
'<td>'.$row['DFP'].'</td>'.
'<td>'.$row['SIM'].'</td>'.
'<td>'.$row['Prereqs'].'</td>'.
'<td>'.$row['Design'].'</td>'.
'<td>'.$row['Report'].'</td>'.
'<td>'.$row['Delivered'].'</td>'.
'<td>'.
'<a href="#">'.
'<span class="edit"><i class="fa fa-pencil"></i></span>'.
'</a> | <a href="#">'.
'<span class="delete"><i class="fa fa-times"></i></span>'.
'</a>'.
'</td>'.
'</tr>'.
'</tbody>';
}
echo "</table>";
}
else
echo "0 results";
$conn->close();
That all works fine, but now I want to have what is essentially a delete button (you can see the markup above that creates the icon/link) that will populate automatically to correspond with the appropriate ID for the mysql database table. Image of table for visual idea of what I'm going for.
My delete script so far is below, but I have no idea what to put in the "WHERE id=", or how to incorporate it into my first script once it's setup properly.
<?php
require_once('dbconnect.php');
$sql = "DELETE FROM Predictions WHERE id=";
if($conn->query($sql) === TRUE)
echo "Item deleted successfully";
else
echo "Error deleting record; ". $conn->error;
$conn->close();
So basically I need advice to modify both of these scripts so that a delete link (or form, I don't care) is generated in the first script then applies the second script and it knows the corresponding id to use. In my search to solve this problem I saw some potential solutions using _GET, but in the same thread others said that is in fact a very bad and insecure solution.. so I'm very confused!
I'm learning PHP as I go, and I've only been going at it for about 2 days, so please have mercy :)
Change this
<a href='#'><span class='delete'>
to
<a href='deletepage.php?id=" . $row["ID"] . "'><span class='delete'>
then on "deletepage.php", whatever you are going to call that page do something like
require_once('dbconnect.php');
$id = (int)$_GET['id'];
$sql = "DELETE FROM Predictions WHERE id=" . $id;
if($conn->query($sql) === TRUE) {
echo "Item deleted successfully";
} else {
echo "Error deleting record; ". $conn->error;
}
$conn->close();
I don't know what driver you are using here but the preferred solution would be using a prepared statement with a parameterized query.
So pretty much you send the id via a GET parameter to your "delete page". That page takes that value, casts it to an int to avoid SQL injections (read further below), and then deletes the data. You also could instead of echoing a success there use a header to redirect them to the previous page. You could append a GET parameter to that url display a success message. (or you could always do all this on the same page and just check if the id is being sent).
Also you should have this page behind someone secure login system. You don't want any user/bot able to execute that deletepage.php.
How can I prevent SQL injection in PHP? http://php.net/manual/en/security.database.sql-injection.php https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28Parameterized_Queries.29
I'm guessing you are using mysqli so take a look at this doc for prepared statements with that driver, http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.
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 have a PHP script that reads a database table and inserts all the rows into an HTML table until it's displayed all available rows as shown here:
require_once('dbconnect.php');
$sql =
"SELECT
ID, Site, Type, Requested, Quote,
PO, CADs, MCS, DFP,
SIM, Prereqs, Design, Report, Delivered
FROM Predictions";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<table class="table table-hover table-condensed">';
while($row = $result->fetch_assoc()) {
echo
'<tbody>'.
'<tr>'.
'<td>'.$row['ID'].'</td>'.
'<td>'.$row['Site'].'</td>'.
'<td>'.$row['Type'].'</td>'.
'<td>'.$row['Requested'].'</td>'.
'<td>'.$row['Quote'].'</td>'.
'<td>'.$row['PO'].'</td>'.
'<td>'.$row['CADs'].'</td>'.
'<td>'.$row['MCS'].'</td>'.
'<td>'.$row['DFP'].'</td>'.
'<td>'.$row['SIM'].'</td>'.
'<td>'.$row['Prereqs'].'</td>'.
'<td>'.$row['Design'].'</td>'.
'<td>'.$row['Report'].'</td>'.
'<td>'.$row['Delivered'].'</td>'.
'<td>'.
'<a href="#">'.
'<span class="edit"><i class="fa fa-pencil"></i></span>'.
'</a> | <a href="#">'.
'<span class="delete"><i class="fa fa-times"></i></span>'.
'</a>'.
'</td>'.
'</tr>'.
'</tbody>';
}
echo "</table>";
}
else
echo "0 results";
$conn->close();
That all works fine, but now I want to have what is essentially a delete button (you can see the markup above that creates the icon/link) that will populate automatically to correspond with the appropriate ID for the mysql database table. Image of table for visual idea of what I'm going for.
My delete script so far is below, but I have no idea what to put in the "WHERE id=", or how to incorporate it into my first script once it's setup properly.
<?php
require_once('dbconnect.php');
$sql = "DELETE FROM Predictions WHERE id=";
if($conn->query($sql) === TRUE)
echo "Item deleted successfully";
else
echo "Error deleting record; ". $conn->error;
$conn->close();
So basically I need advice to modify both of these scripts so that a delete link (or form, I don't care) is generated in the first script then applies the second script and it knows the corresponding id to use. In my search to solve this problem I saw some potential solutions using _GET, but in the same thread others said that is in fact a very bad and insecure solution.. so I'm very confused!
I'm learning PHP as I go, and I've only been going at it for about 2 days, so please have mercy :)
Change this
<a href='#'><span class='delete'>
to
<a href='deletepage.php?id=" . $row["ID"] . "'><span class='delete'>
then on "deletepage.php", whatever you are going to call that page do something like
require_once('dbconnect.php');
$id = (int)$_GET['id'];
$sql = "DELETE FROM Predictions WHERE id=" . $id;
if($conn->query($sql) === TRUE) {
echo "Item deleted successfully";
} else {
echo "Error deleting record; ". $conn->error;
}
$conn->close();
I don't know what driver you are using here but the preferred solution would be using a prepared statement with a parameterized query.
So pretty much you send the id via a GET parameter to your "delete page". That page takes that value, casts it to an int to avoid SQL injections (read further below), and then deletes the data. You also could instead of echoing a success there use a header to redirect them to the previous page. You could append a GET parameter to that url display a success message. (or you could always do all this on the same page and just check if the id is being sent).
Also you should have this page behind someone secure login system. You don't want any user/bot able to execute that deletepage.php.
How can I prevent SQL injection in PHP? http://php.net/manual/en/security.database.sql-injection.php https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28Parameterized_Queries.29
I'm guessing you are using mysqli so take a look at this doc for prepared statements with that driver, http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.
I am using this code to get data from Json and insert them to mysql. However it inserts no records in the data base.
<?php
include("db.php");
$currsiteurl = 'http://graph.facebook.com/1597233119';
$graph = json_decode(file_get_contents($currsiteurl));
$id = $graph->id;
echo "id : ".$id;
echo "<br>";
$username = $graph->username;
echo "username : ".$username;
echo "<br>";
$gender = $graph->gender;
echo "gender : ".$gender;
echo "<br>";
$locale = $graph->locale;
echo "locale : ".$locale;
mysql_query("INSERT INTO users_data (id, username, gender, locale)
VALUES ('.$id', '.$username', '.$gender', '.$locale')");
?>
Can any one show me whereis the mistake ?
mysql_query("INSERT INTO users_data (id, username, gender, locale)
VALUES ('.$id', '.$username', '.$gender', '.$locale')");
You are creating a single string (with embedded variables) so the dots '.' are not required.
If either of the id or gender are number-fields then this is likely to be what prevents the data from being inserted (with the dots). (If they are numbers they don't require surrounding apostrophes either.)
In addition to what Andy G states:
You should use prepared statements to make sure the data you are receiving is properly escaped to avoid sql injection attacks: http://php.net/manual/en/pdo.prepared-statements.php
To assist debugging queries, add echo mysql_error() after your mysql_query statement to print the error (or use one of the new fangled methods mentioned in the alert here: http://us1.php.net/manual/en/function.mysql-error.php)
I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.