Delete MySQL PHP - php

mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$insert="INSERT INTO inactive (ID_No, User_Password, First_Name, Last_Name, Email, Contact_Number)
VALUES('". $ID_No ."','". $UserPassword ."','". $FirstName ."','". $LastName ."','". $Email ."','". $ContactNumber ."')";
$result=mysql_query($insert);
$sql="DELETE FROM users WHERE ID_No = '$ID_No'";
$result2=mysql_query($sql);
if($result && $result2){
echo"Successful!";
} else {
echo "&nbsp Error";
}
Hi guys I have been stuck in delete function of MySQL, I have tried searching the net but when I ran my code it always goes to the else part which means there is an error, the insert is already okay but the delete is not.

PHP variables are allowed in double quotes. Hence try this,
$sql="DELETE FROM users WHERE ID_No = $ID_No";

Your first query was not properly escaped. Rewrite like
$insert="INSERT INTO inactive (`ID_No`, `User_Password`, `First_Name`, `Last_Name`, `Email`, `Contact_Number`)
VALUES('$ID_No','$UserPassword','$FirstName','$LastName','$Email','$ContactNumber')";
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

First, use PDO.
Make your connection Database like this:
function connectToDB(){
$host='localhost';
try {
$user = 'username';
$pass = 'password';
$bdd = 'databaseName';
$dns = 'mysql:host='.$host.';dbname='.$bdd.'';
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
return $connexion = new PDO($dns, $user, $pass, $options);
}catch ( Exception $e ) {
echo "Fail to connect: ", $e->getMessage();
die();
}
}
To delete something, here is an example:
function deleteUserWithId($ID_No){
$connexion = connectToDB();
try{
$connexion->exec('DELETE FROM users WHERE ID_No = '.$ID_No);
}catch(Exception $e){
echo "Error: ".$e->getMessage();
}
}
To insert something:
function addInactiveUser($UserPassword,$FirstName ,$LastName ,$Email,$ContactNumber){
$connexion = connectToDB();
$insert = $connexion->prepare('INSERT INTO inactive VALUES(:ID_No,
:User_Password,
:First_Name,
:Last_Name,
:Email,
:Contact_Number
)');
try {
// executing the request
$success = $insert->execute(array(
'ID_No'=>'',
'User_Password'=>$UserPassword,
'First_Name'=>$FirstName ,
'Last_Name'=>$LastName ,
'Email'=>$Email,
'Contact_Number'=>$ContactNumber
));
if($success)
// OK
else
// KO
}
catch (Exception $e){
echo "Error: ".$e->getMessage();
}
}
To make a select:
// If you want to display X user per pages for example
function getAllInactiveUsers($page, $numberInactiveUserPerPage){
$connexion = connectToDB();
$firstInactiveUser = ($page - 1) * $numberInactiveUserPerPage;
$selectAllInactiveUsers = $connexion->prepare('SELECT * FROM inactive ORDER BY ID_No DESC LIMIT '.$firstInactiveUser.','.$numberInactiveUserPerPage);
return $selectAllInactiveUsers ;
}
To get the results of this methods, just do something like this:
$inactiveUsers= getAllInactiveUsers(1,15); // for page 1, display 15 users
$inactiveUsers->execute();
while($row = $inactiveUsers->fetch(PDO::FETCH_OBJ)){
$id = $row->ID_No;
$first_name = $row->First_Name;
// etc...
}
Hope that's help :)

I am not sure if this helps you, but as an alternative you could delete the last entry in the table:
$delQ = mysql_query("SELECT * FROM ph ORDER BY id DESC LIMIT 1" );
while(( $ar = mysql_fetch_array($delQ)) !== false){
mysql_query("DELETE FROM ph WHERE id= $ar[id]");
}

Related

Updating database using dropdown without using a submit button

I'm trying to update the table status value whenever I make a selection from the dropdown list.
The problem is I'm having a syntax error on my update query. I've read stuff about syntax error and I can't quite understand it. I think I'm gonna need a more specific help. Here's what I've done:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$databasename = "companydb";
try
{
$conn = new PDO("mysql:host=$hostname;dbname=$databasename",$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["status"]))
{
$query = "UPDATE tickets SET status = '$status' WHERE id = $id";
$statement = $conn->prepare($query);
$statement->execute(array('status' => $_POST["status"]));
$count = $statement->rowCount();
if($count > 0)
{
echo "Data Inserted Successfully..!";
}
else
{
echo "Data Insertion Failed";
}
}
else
{
echo "unknown index: 'status'";
}
}
catch(PDOException $error)
{
echo $error->getMessage();
}
?>
And here's my table schema:
You are not performing prepared statements properly. You need to add the placeholder in the query and not the variables. The variables should be added in the execute() line.
$query = "UPDATE tickets SET `status` = :status WHERE `id` = :id";
$statement = $conn->prepare($query);
$statement->execute(array(':status' => $_POST["status"],':id' => $id));
Also FYI, $id is undefined.
Try Changing this:
$query = "UPDATE tickets SET status = $status WHERE id = $id";

php/pdo insert into database mssql with arrays

I need some help
Is there a way to make this in PDO? https://stackoverflow.com/a/1899508/6208408
Yes I know I could change to mysql but I use a mssql server and can't use mysql. I tried some things but I'm not as good with PDO as mysql... It's hard to find some good examples of inserting array's into database with PDO. So quickly said I have a PDO based code connected to a mssql webserver.
best regards joep
I tried this before:
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$data = array_merge($mon_barcode, $mon_merk, $mon_type, $mon_inch, $mon_a_date, $mon_a_prijs);
try{
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
$insertData = array();
foreach($_POST['mon_barcode'] as $i => $barcode)
{
$insertData[] = $barcode;
}
if (!empty($insertData))
{
implode(', ', $insertData);
$stmt = $conn->prepare($sql);
$stmt->execute($insertData);
}
}catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
The code below should fix your problems.
$db_username='';
$db_password='';
$conn = new \PDO("sqlsrv:Server=localhost,1521;Database=testdb", $db_username, $db_password,[]);
//above added per #YourCommonSense's request to provide a complete example to a code fragment
if (isset($_POST['com_id'])) { //was com_id posted?
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
try {
$stmt = $conn->prepare($sql);
foreach ($mon_barcode as $i => $barcode) {
$stmt->execute([$com_id, $barcode, $mon_merk[$i], $mon_type[$i], $mon_inch[$i], $mon_a_date[$i], $mon_a_prijs[$i]]);
}
} catch (\PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
$conn = null;

mysqli update not updating although no error

I am trying to adapt my code, which works in a SELECT, to perform an UPDATE. Here, there is no error, but it does not update anything, it even does not even enter the loop. It is supposed to update the room type for the chosen days ($value).
I echoed all values to check them up and they are correct.
$bdd = mysqli_connect('localhost', 'root', '', 'webpage')
$roomty = 1;
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
foreach ($_SESSION['datesBooked_1_month'] as $key => $value)
{
$stmt = mysqli_stmt_init($bdd);
if ( mysqli_stmt_prepare( $stmt , "UPDATE '".$_SESSION['tab_from_month_year']."'
SET '".$_SESSION['roomtype_x']."'='".$_SESSION['roomtype_x']."' + ? WHERE day = ?"))
{
mysqli_stmt_bind_param( $stmt ,'is', $roomty , $value );
mysqli_stmt_execute( $stmt );
mysqli_stmt_close($stmt);
echo " Booked !<br /> ";
}
}
Please try the following code with the new MySql driver of PHP.
you put the quote for a integer value, that is wrong
do you named column with numbers? That is not comfortable.
Are you sure that $value is a string?
Why did you use $key => $value in the foreach loop?
Here the code:
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=webpage;host=127.0.0.1';
$user = 'root';
$password = 'dbpass'; #put here yor password
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
foreach $_SESSION['datesBooked_1_month'] as $value) {
#I hope that following variables don't contain space
$query = "UPDATE " .$_SESSION['tab_from_month_year'];
$temp = $_SESSION['roomtype_x'] + $roomty ;
#you wrote that $value is a string, are you sure?
$query .= " SET ".$_SESSION['roomtype_x']. "=$temp WHERE day='$value'" ;
$dbh->query($query);
}
I found out, the problem was the single quotes before the double quotes. It seems to be working very well with only double quotes like this :
if ( mysqli_stmt_prepare( $stmt , "UPDATE ".$_SESSION['tab_from_month_year']." SET ".$_SESSION['roomtype_x']." = ".$_SESSION['roomtype_x']." + ? WHERE day = ?"))
If this is the full code you need to select a database, currently the statement is being sent to the server but not to any database, there for you get no errors. You should use:
mysqli_select_db("You database goes here");

How to check if there is value or not using MySQL/PHP

Well here is the script:
<?php
session_start();
$con = mysql_connect("localhost","***","***");
mysql_query("SET NAMES UTF8");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("**8", $con);
$sql = mysql_query("TRUNCATE TABLE headset");
$qry= "INSERT INTO `headset` (`WebTitle`) VALUES ('". $_POST[webtitle] ."')";
$sql = mysql_query("TRUNCATE TABLE headset2");
$qry= "INSERT INTO `headset2` (`WebSlogan`) VALUES ('". $_POST[webslogan] ."')";
if (!mysql_query($qry,$con))
{
die('Error: ' . mysql_error());
}
header("location: ../generalsettings.php");
exit();
mysql_close($con);
?>
This is just for the one value:
I have a form with 2 boxes and I want to achieve the following: if only one of the boxes is filled I would like to truncate and insert only the value that is filled, and do nothing with the other unfilled box.
I hope you got my point.
Don't use the mysql_query functions!!! Better use the pdo class
http://php.net/manual/de/book.pdo.php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');
if (isset($_POST['webtitle']) && $_POST['webtitle'] != '') {
try {
$db->query('TRUNCATE TABLE headset');
$stmt = $db->prepare("INSERT INTO headset (WebTitle) VALUES (?)");
$stmt->bindParam(1, $_POST[webtitle]);
$stmt->execute();
} catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
}
}
to check if there is value in database do this
$myquery= mysql_query(" select * from headset ");
if(mysql_fetch_row($myquery)==0){ --//there is no data in your database
}
else { --//there is data do what you like
}
*please use mysqli or PDO instead of mysql
if (isset($_POST['webtitle']) && $_POST['webtitle'] != '') {
// $_POST['webtitle'] code here
}
if (isset($_POST['webslogan']) && $_POST['webslogan'] != '') {
// $_POST['webslogan'] code here
}
And the same for the other one

Select data from database and update it PHP/PDO

I need to make a PHP code that gets data from server, updates it and echos that updated data to user. I am beginner with PHP so I have no idea how to do this. This is the code I have have now.
So how do I change the code to make it update data ?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
one idea is to create a different database connection file consisting of a pdo connection and reuse it in your application. on how to do that.
in database.php you can do it like
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
and everywhere you want to use the connection you can do
require_once 'Database.php';
and some of the sample CRUD (Create, Read, Update, Delete) using PDO are.
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
you should also study about named and unnamed placeholders, to escape SQL injections etc. you can read more about PDO with a very easy to understand tutorial by nettuts here
hope this helps you.
Try this. I think it is along the lines of what you are looking for:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = #mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( #mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>

Categories