So I have an issue getting rows to be deleted using the following code. The table displays the information correctly, plus sends the correct id in the url to the delete.php page, but I cannot get it to complete the command. Changing the code slightly on the delete.php I can get it to show either:
Couldn't delete the index.
or:
Binding parameters failed: 0
<?php
$con = mysqli_connect("localhost","user","pass","database");
// Check connection
if (mysqli_connect_errno())
{
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
if (!$result = mysqli_query($con,"SELECT * FROM mytable ORDER BY `server_name`;"))
{
die("Error: " . mysqli_error($con));
}
?>
<table border='1'>
<tr>
<th><b>Server Name</b></th>
<th><center><b>Port</b></center></th>
<th><center><b>Mod</b></center></th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['server_name']; ?></td>
<td><center><?php echo $row['server_port']; ?></center></td>
<td><center><?php echo $row['mod']; ?></center></td>
<td><center><img src="images/remove.png" width="16" height="16"></center></img></td>
</tr>
<?php
}
mysqli_close($con);
?>
</table>
My delete file is
<?php
// Your database info
$db_host = 'localhost';
$db_user = 'user';
$db_pass = 'pass';
$db_name = 'database';
if (!isset($_GET['id']))
{
echo 'No ID was given...';
exit;
}
$con = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
{
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}
$sql = "DELETE FROM mytable WHERE 'index' = " . $_GET['id'];
if (!$result = $con->prepare($sql))
{
die('Query failed: (' . $con->errno . ') ' . $con->error);
}
if (!$result->bind_param('i', $_GET['ID']))
{
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
if (!$result->execute())
{
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
if ($result->affected_rows > 0)
{
echo "The ID was deleted with success.";
}
else
{
echo "Couldn't delete the index.";
}
$result->close();
$con->close();
It has to be something simple but I cannot figure it out.
You're using the wrong type of quotes in your SQL. To escape a table or column name that contains a reserved word, you use backticks. And if you're using bind_param, you have to put ? in the query where the parameter will be substituted.
$sql = "DELETE FROM mytable WHERE `index` = ?";
Replace the following line in your delete.php file:
$sql = "DELETE FROM mytable WHERE 'index' = " . $_GET['id'];
with:
$sql = "DELETE FROM mytable WHERE `index` = ?";
Changes in the suggested replacement statement include:
Replace single quotes around column name index with backticks. Note that MySQL escape character is a backtick not single quotes.
You are not including any parameter placeholders in your delete query but further down you are attempting to bind an integer parameter.
Related
I have a list of items that is being output via PHP / MySQL. I also have an Edit button and a Delete button in one column. I am trying to figure out how to delete a list item on a specific row by clicking the Delete button. I have tried the following:
$id = $_GET['id'];
if(isset($_POST["deletelist"])) {
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '$id'";
} else {
echo "Cannot delete";
}
}
This of course does not work. Can anyone help me out with this?
UPDATE
This is the code for the entire page:
https://pastebin.com/raw/qjnZkUU2
UPDATED CODE
$id = $_GET['id'];
if(isset($_POST["deletelist"])) {
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '$id'";
mysqli_query($db, $query);
} else {
echo "Cannot delete";
}
}
What I am confused about is how does the query know which item to delete? Should I be appending the ID to the URL to pass the ID?
UPDATE
Ok I think I get it....In the delete button, I need to echo the ID of that row so when the query runs from clicking the delete button, it knows which ID to delete correct?
RESOLVED
Alright. I got it figured out!
I have a button that references the ID of the list item:
echo "
I then pass that ID to deletelist.php
if (!isset($_GET['id'])) {
echo 'No ID was given...';
exit;
}
if ($db->connect_error) {
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}
$sql = "DELETE FROM lists WHERE id = ?";
if (!$result = $db->prepare($sql)) {
die('Query failed: (' . $db->errno . ') ' . $db->error);
}
Item gets deleted.
you have to execute query for any action in database
mysqli_query($db, $query);
so execute a delete query and then try it again
You have to execute the query. There is no query execution code. Try this
$id = $_GET['id'];
if(isset($_POST["deletelist"])) {
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '$id'";
mysqli_query($db, $query);
} else {
echo "Cannot delete";
}
}
In order to delete a specific row what I needed to do was echo the ID within a link/button. This would then pass the ID to the needed PHP to delete the row from the database.
Echoing the row ID in the button
echo "
The PHP to delete the action row
<?php
include("db.php");
if (!isset($_GET['id'])) {
echo 'No ID was given...';
exit;
}
if ($db->connect_error) {
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}
$sql = "DELETE FROM lists WHERE id = ?";
if (!$result = $db->prepare($sql)) {
die('Query failed: (' . $db->errno . ') ' . $db->error);
}
if (!$result->bind_param('i', $_GET['id'])) {
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
if (!$result->execute()) {
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
if ($result->affected_rows > 0) {
echo "The ID was deleted with success.";
} else {
echo "Couldn't delete the ID."; }
$result->close();
$db->close();
header('Location: ../account.php');
?>
This deletes the item row and then returns the user to account.php. Which in this case, the page never really changes.
Try like below
if(isset($_POST["deletelist"]) && isset($_GET['id']) ) {
$id = $_GET['id'];
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '".mysqli_real_escape_string($db,$id)."'";
mysqli_query($db, $query);
} else {
echo "Cannot delete";
}
}
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
So I'm new to mysqli. All of the examples I find online seem to be the old (procedural) way of doing things. Can someone tell me why my code isn't working below? My db is 'templatedb'. My Table is 'template'. I have one entry in my table, but I'm receiving no output with my echo. I'm not getting any errors with my code.
<div id="templateSelector">
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "templatedb";
//connect
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$database = mysqli_connect($hostname, $username, $password, $db);
if(!$database){
die("Could not connect to the database");
}
if ($database->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
$sql = "SELECT * FROM template";
if (!$result = $database->query($sql)) {
die('There was an error running the query [' . $db->error . ']');
} else {
echo "<label>Select Template</label>";
echo "<select name='templates'>";
while ($row = $result->fetch_assoc()) {
echo "hello";
echo $row['template_name'];
// echo "<option value='" . $row['template'] . "'>" . $row['template'] . "</option>";
}
echo "</select>";
}
}
?>
Try doing the following, worked for me
<div id="templateSelector">
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "templatedb";
$mysqli = mysqli_connect($hostname, $username, $password, $db);
if($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
$sql = "SELECT * FROM template";
$result = mysqli_query($mysqli, $sql);
if(!$result = $mysqli->query($sql)) {
die('There was an error running the query [' . $db->error . ']');
} else {
echo "<label>Select Template</label>\n";
echo "<select name='templates'>\n";
while($row = $result->fetch_assoc()) {
echo "<option>id = " . $row['id'] . "</option>\n";
}
echo "</select>";
}
}
?>
</div>
Make sure your DATABASE is called templatedb and the table it is in is called template and there is a row called id. I know that sounds trivial, but spelling mistakes will break your code.
I do not understand what is going wrong with code. The result is get is "connected successfully success Query failed". I tried few combinations and I get the same result. Please help me in solving this. Thanks in advance.
<?php
$link = mysql_connect('localhost', 'root1', '')
or die('Could not connect: ' . mysql_error());
if ($link) {
echo 'connected successfully';
}
$l = mysql_select_db('vtflix', $link) or die ('Could not select the database');
if ($l) {
echo ' success';
}
/*$varCNAME = 'John';
$varCONTENT = '4';
$varVID = '1';*/
$sql = "INSERT INTO mpaa(C_Name, ContentRating, V_ID) VALUES ('Jon', 4, 3)";
mysql_query($sql, $link) or die("Query failed");
$que = "SELECT * FROM mpaa";
$query = mysql_query($que, $link);
if (!$query) {
echo 'query failed';
}
while ($sqlrow = mysql_fetch_array($query, MYSQL_ASSOC)) {
$row = $sqlrow['C_Name'];
$nrow = $sqlrow['Content Rating'];
$mrow = $sqlrow['V_ID'];
echo "<br>" . $row . " " . $nrow . " " . $mrow . "<br>";
}
mysql_close($link);
?>
1.Don't use mysql_* library (deprecated from php5 onward + removed from php7) .Use mysqli_* OR PDO.
2.An example of mysqli_*(with your code)is given below:-
<?php
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors
$link = mysqli_connect('localhost', 'root1', '','vtflix');
if($link){
echo 'connected successfully';
$sql= "INSERT INTO mpaa(C_Name,ContentRating,V_ID) VALUES ('Jon', 4, 3)";
if(mysqli_query($link,$sql)){
$query = "SELECT * FROM mpaa";
$res = mysqli_query($link,$query);
if($res){
while($sqlrow=mysqli_fetch_assoc($query))
{
$row= $sqlrow['C_Name'];
$nrow= $sqlrow['Content Rating'];
$mrow= $sqlrow['V_ID'];
echo "<br>".$row." ".$nrow." ".$mrow."<br>";
}
mysqli_close($link);
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Could not connect: ' . mysqli_connect_error());
}
?>
Note:- To check php version (either on localhost or on live server) create a file with name phpInfo.php, and just write one line code in that file:-
<?php
phpinfo();
?>
Now run this file and you will get the current php version.
Like this:- https://eval.in/684551
Here it seems that you are using deprecated API of mysql_* .
1) Check your PHP version
<?php phpinfo();exit;//check version ?>
2) avoid the usage of mysql use mysqli or PDO
3) change your db connection string with this :
new Mysqlidb($hostname, $username, $pwd, $dbname);
example with you code
<?php
$link = mysqli_connect('localhost', 'root1', '','vtflix');
if($link){
echo 'connected successfully';
$sql= "INSERT INTO mpaa(C_Name,ContentRating,V_ID) VALUES ('Jon', 4, 3)";
if(mysqli_query($link,$sql)){
$query = "SELECT * FROM mpaa";
$res = mysqli_query($link,$query);
if($res){
while($sqlrow=mysqli_fetch_assoc($query))
{
$row= $sqlrow['C_Name'];
$nrow= $sqlrow['Content Rating'];
$mrow= $sqlrow['V_ID'];
echo "<br>".$row." ".$nrow." ".$mrow."<br>";
}
mysqli_close($link);
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Could not connect: ' . mysqli_connect_error());
}
?>
Essentially, i'm trying to show the information about what the user has it lists their
BookID date time confirmed
confirmed is a 0 or 1, 0 is not confirmed 1 is confirmed, as this is a table this needs to be done with $_GET i'm assuming or it wont update the correct one.
at the moment I have this for the table listing the things
<?php
while($row = mysqli_fetch_array($result))
{ ?>
<tr>
<td><?php echo $row['BookID']?></td>
<td> <?php echo $row['date']?> </td>
<td> <?php echo $row['time']?> </td>
<td> <input type="checkbox" name="Confirmed" value="1" <?php echo ($row['Confirmed'] == 1) ? 'checked="checked"' : ''; ?>/> </td>
<td>Delete</td>
<td>Update</td>
</tr>
</table>
update.php contains this
<?php
// Your database info
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'smithrwg_database';
$Confirmed = $_POST['Confirmed'];
if (!isset($_POST['Confirmed']))
{
echo 'No ID was given...';
exit;
}
$con = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
{
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}
$sql = mysql_query("UPDATE tbl_booking SET Confirmed = '$Confirmed' WHERE BookID = ?");
//$sql = "UPDATE tbl_booking SET Confirmed='$Confirmed' WHERE BookID == ?";
if (!$result = $con->prepare($sql))
{
die('Query failed: (' . $con->errno . ') ' . $con->error);
}
if (!$result->bind_param('i', $_GET['BookID']))
{
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
if (!$result->execute())
{
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
if ($result->affected_rows > 0)
{
echo "The ID was updated with success.";
}
else
{
echo "Couldn't update the ID.";
}
$result->close();
$con->close();
with my main focus being on the $sql, as it isnt actually getting the id from the get function.
the checkbox is getting the value from the database to see if it should be checked already or not, i want to be able to click it again and "un-confirm" or confirm it if it didn't have a tick.
What did you use for method attribute in your form tag? If you use GET, then use a GET to fetch it. If you use POST, then use a POST. By the way, try to echo all of the posted variables first so that you know that you are passing correct variable. It is always a good debugging method. Hope this helps. Thank you.
I am trying use mysqli functions but I get this error:
Fatal error: Call to undefined method mysqli::num_rows() in C:\AppServ\www\edu\files\header.php on line 19
I tried to go to php.ini and remove ; from extension=php_mysqli.dll
I found it already removed
I tried to restart appachi;
the connection file:
// db username
define("USERNAME","root");
// db password
define("PASSWORD","root");
// db servername
define("SERVERNAME","localhost");
// db name
define("NAME","edu");
//connect to db
$mysqli = new mysqli(SERVERNAME,USERNAME,PASSWORD,NAME);
if ($mysqli->connect_errno) {
echo $cannot_connect;
}
//select db encoding
$mysqli->set_charset('utf8');
calling function in a file:
$sql = $mysqli->query("SELECT VALUE FROM SITE_CONFIG WHERE CONF='KEYWORDS'");
if (!$sql) {
echo "Failed to run query: (" . $mysqli->errno . ") " . $mysqli->error;
}
if($mysqli->num_rows($sql) > 0){
while($rs = $sql->fetch_assoc()){
$keyw = $rs['VALUE'];
}
}else{
$keyw = $no_data;
}
note : I included connection.php
Try:
$sql = $mysqli->query("SELECT VALUE FROM SITE_CONFIG WHERE CONF='KEYWORDS'");
if (!$sql) {
echo "Failed to run query: (" . $mysqli->errno . ") " . $mysqli->error;
} else {
if($sql->num_rows > 0){// here must be $sql , not $mysqli
while($rs = $sql->fetch_assoc()){
echo $rs['VALUE'];
}
} else{
echo "No data";
}
}