Delete a users data from SQL using PHP - php

Hi im trying to delete a users booking detials when the user clicks delete in my bookingbeforedeltion.php file but for some reason when I test my php file once I click delete it goes to my delete.php screen and says it failed to delete from database and has the error Undefined index: rn. Is my rn not defined? Sorry Im new to this. Here is my code below:
bookingbeforedeltion.php:
<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
<body>
<?php
include "config.php";
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);
if (!$DBC) {
echo "Error: Unable to connect to MySQL.\n".
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit;
};
echo "<pre>";
$query = 'SELECT roomname, checkindate, checkoutdate FROM booking';
$result = mysqli_query($DBC,$query);
if (mysqli_num_rows($result) > 0) {
echo "Delete Bookings" ?><p><?php
while ($row = mysqli_fetch_assoc($result)) {
echo "Room name: ".$row['roomname'] . PHP_EOL;
echo "Check in date: ".$row['checkindate'] . PHP_EOL;
echo "Check out date: ".$row['checkoutdate'] . PHP_EOL;
?>
[Cancel]
<?php
echo "<hr />";
}
mysqli_free_result($result);
}
echo "</pre>";
echo "Connectted via ".mysqli_get_host_info($DBC);
mysqli_close($DBC);
?>
</body>
</html>
delete.php:
<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
body>
<?php
include "config.php";
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);
if (!$DBC) {
echo "Error: Unable to connect to MySQL.\n".
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit;
};
echo "<pre>";
$roomname=$_GET['rn'];
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname =
'$roomname'";
$result = mysqli_query($DBC,$query);
if($result)
{
echo "<font color='green'> Booking deleted from database";
}
else {
echo "<font color='red'> Failed to delete booking from database";
}
?>

and I think this will help:
As mentioned above, you need to print it from the PHP
<a href= 'delete.php?rn=$result[roomname]'>
// To
<a href= 'delete.php?rn=<?= $row['roomname'] ?>'>
// Explanation:
// 1. <?= ... ?> is the short form of <?php echo ... ?>
// 2. The `roomname` came from $row, not $result ($result is the MySQLi Object)
// 3. You need to quote the `roomname` because without it `roomname` will be readed
// as Constant, and may Throw a Warning message
//
Your DELETE is incorrect, the correct one is DELETE FROM ... WHERE ...
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname =
'$roomname'";
// To
$query = "DELETE FROM booking WHERE roomname = '$roomname'";
EXTRA:
3. You can assign a default value to $roomname
$roomname=$_GET['rn'];
// To
$roomname=$_GET['rn'] ?? 'default if null';
// if the rn index doesnt exist, the $roomname value will be `default if null` instead of throwing a Warning
Try to use Prepared-Statement SQL instead of writing it. (I dont know the example, but it can prevent SQL Injection)

Related

How to insert data from a select query using php

I wan to insert data to mysql table from another database which is connected via ODBC.But I cannot enter into the while loop, here is my code -
N.B: For security I dont provide db name, user and pass.
ODBC connection declared as 'connStr'
<?php
$connStr = odbc_connect("database","user","pass");
$conn = mysqli_connect("server","user","pass","database");
//$result_set=mysqli_query($conn,$datequery);
//$row=mysqli_fetch_array($result_set);
echo "<br>";
echo "<br>";
$query="select cardnumber, peoplename, creditlimit, ROUND(cbalance,2) as cbalance, minpay from IVR_CardMember_Info
where cardnumber not like '5127%'" ;
$rs=odbc_exec($connStr,$query);
$i = 1;
while(odbc_fetch_row($rs))
{ //echo "Test while";
$cardnumber=odbc_result($rs, "cardnumber");
$peoplename=odbc_result($rs, "peoplename");
$creditlimit=odbc_result($rs, "creditlimit");
$cbalance=odbc_result($rs, "cbalance");
$minpay=odbc_result($rs, "minpay");
$conn = mysqli_connect("server","user","pass","database");
$sql= "INSERT INTO test_data(cardnumber, peoplename, creditlimit, cbalance, minpay) VALUES ('cardnumber', 'peoplename', 'creditlimit', 'cbalance', 'minpay') ";
if(!(mysqli_query($conn,$sql))){
//echo "Data Not Found";
echo "<br>";
}
else{
echo "Data Inserted";
echo "<br>";
}
echo $i++ ;
}
echo "<br>";
odbc_close($connStr);
?>
How can I solve this?
If you really want to understand why you can't enter while() {...}, you need to consider the following.
First, your call to odbc_connect(), which expects database source name, username and password for first, second and third parameter. It should be something like this (DSN-less connection):
<?php
...
$connStr = odbc_connect("Driver={MySQL ODBC 8.0 Driver};Server=server;Database=database;", "user", "pass");
if (!$connStr) {
echo 'Connection error';
exit;
}
...
?>
Second, check for errors after odbc_exec():
<?php
...
$rs = odbc_exec($connStr, $query);
if (!$rs) {
echo 'Exec error';
exit;
}
...
?>
you can do it with just SQL check it here, like:
INSERT INTO test_data(cardnumber, peoplename, creditlimit, cbalance, minpay)
SELECT cardnumber, peoplename, creditlimit,
ROUND(cbalance,2) as cbalance, minpay from IVR_CardMember_Info
where cardnumber not like '5127%'

Displaying fields in php from MS Access database

I have a simple studentinfo.accdb. I was able to connect to this database using php. Moreover, the values of the 'ID' column(primary key) are also being displayed. however, the field values are not. The error message is:
Connected
ID : 1
Warning: odbc_result(): Field class not found in
C:\xampp\htdocs\connect\index.php on line 20
The following is my code:-
<?php
$con=odbc_connect("studentinfo", "", "");
if($con)
{
echo "Connected<br>";
}
else
{
echo "Failed";
}
$sql="select * from Table1 WHERE ID = 1";
$result=odbc_exec($con, $sql);
while ($row=odbc_fetch_array($result)) {
echo "ID : ". $row['ID'];
if(isset($_GET['tName'])){
echo "NAME : ". $row['tName'];}
$asd = odbc_result($result, "class");
echo $asd;
// echo "CLASS :".$row['class'];
echo "<br/>";
}
?>
I have used an isset() and clearly the fileds are not set for some reason. Please help!

direct user to another page using php

what is the best way to direct the user to another page given the IF statement is true. i want the page to direct the user to another page using PHP, when the IF statement is run, i tired this but it doesn't work??
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
Below is the full source code for the page.
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<p><span>Room No: </span><?php $room = $_SESSION['g'];
echo $room; // echo's room ?>
</p>
<p><span>Computer No: </span><?php
$select3 = $_POST['bike'];
echo $select3;
?>
</p>
<p><span>Date: </span><?php $date = $_POST['datepicker'];
echo $date; // echo's date
?>
</p>
<p><span>Start Session: </span>
<?php
if(isset($_POST['select1'])) {
$select1 = $_POST['select1'];
echo $select1;
echo "";
}
else{
echo "not set";
}
?>
</p>
<p><span>End Session: </span>
<?php
if(isset($_POST['select2'])) {
$select2 = $_POST['select2'];
echo $select2;
echo "";
}
else{
echo "not set";
}
?>
</p>
</div>
<div id="success">
<?php
$servername = "localhost";
$name = "root";
$password = "root";
$dbname = "my computer";
// Create connection
$conn = mysqli_connect($servername, $name, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM `booked` WHERE
`date` = '{$date}' AND
`computer_id` = '{$select3}' AND
`start_time` = '{$select1}' AND
`end_time` = '{$select2}' AND
`room` = '{$room}'
";
$result = mysqli_query($conn, $query);
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
else
{
$sql = "INSERT INTO booked (date, computer_id, name, start_time, end_time, room)
VALUES ('$date', '$select3', '$username', '$select1', '$select2', '$room')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
</div>
<form action="user.php">
<input type="submit" value="book another" class="bookanother" />
</form>
</div>
</body>
</html>
If the header is sent already, for example you have echo something before then the header will not work, because the header cannot be set after data flow has started, (since php would have already set the default headers for you). So, in this case if that is so, I do the redirect using javascript.
PHP Docs:
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.
WORK-AROUND: This is a function I have written long back and include in controllers.
/**
* Safely redirect by first trying header method but if headers were
* already sent then use a <script> javascript method to redirect
*
* #param string
* #return null
*/
public function safeRedirect($new_url) {
if (!headers_sent()) {
header("Location: $new_url");
} else {
echo "<script>window.location.href = '$new_url';</script>";
}
exit();
}
add the function and simply call:
safeRedirect('index.php');

execute mysql DELETE query on click

i'm kind of a new player in php and sql field.
i'm trying to delete identity from my persons table when clicking on the remove link (or button)
can somebody tell me what am i doing wrong?
this is my php code:
<?php
$db = new DB();
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
$sql ="SELECT f_name, phone, c.id as idc
FROM contacts as c
WHERE c.cg_id = '$cg_id'";
$result = $db->mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article>";
if(isset($_POST['idc'])){
$idco = $_POST['idc'];
$removeQuery = "DELETE FROM contacts as c WHERE id=".$idco." ";
$resultt = mysql_query($removeQuery);
if($resultt) {
header('Location: '.$_SERVER['REQUEST_URI']);
}
echo "<script>window.location.reload(true);</script>";
}
}
}else {
echo "Please edit senior profile for monitoring!";
}
?>
Try this (obviously replacing "localhost", "dbuser", "dbpassword" and "database_name" with the details for your mysql server and database):
<?php
$db = new mysqli("localhost","dbuser","dbpassword","database_name");
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
// I've moved the deletion code to BEFORE the select query, otherwise the
// query will be shown including the to-be-deleted data and it is then deleted after it is displayed
if(isset($_GET["del"])){ // <--- this was $_POST["del"] which would have been unset
$idc = $_GET["del"];
if($db->query("DELETE FROM contacts WHERE id=$idc")){
echo "deleted";
} else {
echo "fail";
}
}
$sql ="SELECT photo, f_name, phone, street, street_num, city, l_name, c.id as idc FROM contacts as c, address as a WHERE c.cg_id = '$cg_id' and a.id = c.address_id";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<article class='contact5 lior'>";
echo "<img class='CSImage' src='" .$row["photo"]."'>";
echo "<section class='generalFormTextW nameCPosition'> " .$row["f_name"]." ".$row["l_name"]."<br></section>";
echo "<section class='generalFormTextW phoneCPosition'> " .$row["phone"]."<br></section>";
echo "<section class='generalFormTextB addressCPosition'>".$row["city"].", <br> ".$row["street"]." ".$row["street_num"]. "<br></section>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article></article>";
}
}
?>
Notice that I'm changing the way you're using mysqli so that you are using it directly rather than as a member of the DB object which is the way I've seen it used elsewhere - It looks to me as if you don't actually open the database connection (although maybe you just didn't include it because it showed your password?)
**EDIT: I've changed $_POST["del"] to $_GET["del"] -- because you are setting del in a url ("contacts2.php?del=") this will be GET not POST.
**EDIT: I've moved the deletion code so that it fixes the problem where you have to refresh the page to see the data with the record deleted - previously the information was shown and THEN deleted, we want to delete THEN show.

Trying to create a simple cumulative addition script in PHP (or JS):

Trying to create a simple cumulative addition script in PHP (or JS):
1) enter any integer(4 digits or less), click submit, number entered is displayed and saved on the same web page
2) enter another number, click submit, number entered is added to previous number and total is saved and displayed on the web page
Repeat …….
Example: the mantra counter at garchen.net
Below is the code I have so far
In Index.php:
<form method="post" action= "process-mantra-form-ami.php" >
<p><strong>Amitabha Million Mantra Accumulation: </strong><br></p>
<div style="margin-left: 20px;">
<p>OM AMI DEWA HRI</p>
<input type="text" name="accumulation" size="10" maxlength="6">
<input type="submit" value="Submit Your Mantra" name="B1"><br>
<span id="mani">Amitabha Mantra Count: <?php echo $newValue; ?> </span>
<p></p>
</div>
</form>
I am getting confused about the form processing php. Im attempting to use my local mamp server for the db. Do I create a connection, create a database, and a table, insert form data into table, and retrieve data back to index.php all at the same time in the process-mantra-form-ami.php file?
You guys made it seem easy in my last post, but there seems to be a lot to it. I know my code below is incomplete and not quite correct. Help!
PROCESS-MANTRA-FORM-AMI.PHP code below
<?php
// Create connection
$con=mysqli_connect("localhost:8888","root","root","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$accumulation = mysqli_real_escape_string($con, $_POST['accumulation']);
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($con);
}
// Create table "Mantras" with one column 'Num'
$sql="CREATE TABLE Mantras (Num INT)";
if (mysqli_query($con,$sql)) {
echo "Table mantras created successfully";
} else {
echo "Error creating table: " . mysqli_error($con);
}
// Insert form data into table
$sql="INSERT INTO Mantras (Num INT)
VALUES ('$num')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
// update database
mysqli_query($con,"UPDATE Mantra SET Num = num + 1");
}
mysqli_close($con);
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>
try this out... (sorry, bored tonight)
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
$conn->query($sql)
$conn->prepare($sql)
$conn->error
http://php.net/manual/en/class.mysqli-stmt.php
$stmt->bind_param('ss',$val1,$val2)
$stmt->bind_result($res1,$res2)
http://php.net/manual/en/mysqli.construct.php
<?php
$host = 'localhost'; // localhost:8888
$user = 'root';
$pass = ''; // root
$dbnm = 'test';
$conn = mysqli_connect($host,$user,$pass,$dbnm)
or die('Error ' . $conn->connect_error);
// for testing.... so i can run the code over and over again and not
// get errors about things existing and stuff
run_statement($conn,"drop database if exists `my_db`;",'cleared old db');
run_statement($conn,"drop table if exists `mantras`;",'cleared old table');
run_statement($conn,"drop table if exists `two_col_table`;",'cleared old table');
// Create database
$sql = 'create database my_db';
$err = run_statement($conn,$sql,'Database creation');
if (!$err) $conn->select_db('my_db');
// Create table "Mantras" with one column 'Num'
$sql = 'create table mantras (num int)';
$err = run_statement($conn,$sql,'Table mantras');
if (!$err) {
$sql = 'insert into mantras (num) values ( ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('d',$num); // d is for digit but s (string) would work too
$num = 1;
$stmt->execute();
$num = 2;
$stmt->execute();
$stmt->close();
echo ($conn->error) ? "insert errored: {$conn->error}" : 'insert ran succesfully';
// update database
$sql = 'update mantras set num = num + 1';
run_statement($conn,$sql,'Update database');
}
// Create table "test" with two columns
$sql = 'create table two_col_tbl (num int, txt varchar(10))';
$err = run_statement($conn,$sql,'Table two_col_tbl');
if (!$err) {
// demonstrating how to bind multiple values
$sql = 'insert into two_col_tbl values ( ?, ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('ds',$num,$txt);
$num = 1; $txt = 'hello';
$stmt->execute();
$num = 2; $txt = 'world';
$stmt->execute();
$stmt->close();
// select statement
$sql = 'select num, txt from two_col_tbl';
$stmt = $conn->prepare($sql);
$stmt->bind_result($db_num, $db_txt);
$stmt->execute();
print '<table><tr><th colspan=2>two_col_tbl</tr><tr><th>num</th><th>txt</th></tr>';
while ($stmt->fetch()) {
print "<tr><td>$db_num</td><td>$db_txt</td></tr>";
}
print '<table>';
$stmt->close();
}
$conn->close();
function run_statement($conn,$statement,$descr) {
if ($conn->query($statement))
echo "$descr ran successfully";
else echo "$descr failed: {$conn->error}";
return $conn->error;
}
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>

Categories