PHP MySql delete query - php

I have a delete script on my dashboard that WAS working before moving domains.
( not sure if that is relevant )
The code for my 'deletejob.php' is below.
<?php
error_reporting(0);
$host = 'localhost';
$port = 3306;
$database = 'database';
$username = 'username';
$password = 'password';
$UID = $_POST["ID"];
// Connect to the database
$dsn = "mysql:host=$host;port=$port;dbname=$database";
$db = new PDO($dsn, $username, $password); // connect
$Query = "DELETE FROM joblist WHERE ID='$UID'";
// Do a query thingy whatever its called
$statement = $db->prepare($Query);
$statement->execute();
while ($result = $statement->fetchObject()) {}
?>
The script functions as if it is working and even gives me the alert
( ID has been successfully deleted. )
Does anyone have any idea as to why this script would return a false positive?

You must find the row you want to delete, using SELECT statement, like this:
$stmt= $conn->query("SELECT * FROM users WHERE id='".$_REQUEST['ids']."'");
Also You have to have the following sent when you click the delete button or it will not delete at all:
<input type="hidden" name="id" value="<?php echo $_REQUEST['ids'];?>">
After the above:
$stmt= $conn->query("DELETE FROM users Where id = '".$_REQUEST['id']."'");

Related

How to insert rows of a table from one database to another (with two PDO)

I would like to insert all the data of a table presented on the database of our network
on a remote database (present on a remote server)
(this action will automate every 30 minutes)
The problem is that I do not see how to retrieve all the data from the table_local and insert them directly into the table_remote.
Indeed, to connect to these two databases, I use PDO
<?php
// LOCAL
$user = 'user1';
$password = 'password1';
$dns = 'completeDNS1';
$bdd = new PDO($dns, $user, $password);
$request = $bdd->prepare("SELECT * FROM table_local");
$request ->execute();
// REMOTE
$user = 'user2';
$password = 'password2';
$dns = 'completeDNS2';
$bdd = new PDO($dns, $user, $password);
// How to insert the previous data on the table_remote ?
?>
I would like to avoid, if possible, the foreach because the script will be launched very often and the table_local contains a lot of line
Is there a simple solution?
One method is using one tool like navicat or sequel pro to achieve.
Another method is using following codes:
$sql = "INSERT INTO table_name (column1, column2...) VALUES ";
foreach($res $key => $val) {
$sql .= "($val['column1'],$val['column2']...),";
}
$sql = rtrim($sql, ',');
...
<?php
// LOCAL
$user = 'user1';
$password = 'password1';
$dns = 'completeDNS1';
$bdd1 = new PDO("mysql:host=localhost;dbname=$dns", $user, $password);
$user = 'user2';
$password = 'password2';
$dns = 'completeDNS2';
$bdd2 = new PDO("mysql:host=localhost;dbname=$dns", $user, $password);
$request = $bdd1->prepare("SELECT * FROM table_local");
// REMOTE
while ($row = $request->fetch()) {
$sql = "INSERT INTO table_remote (name, surname, sex) VALUES (?,?,?)";
$stmt= $bdd2->prepare($sql);
$stmt->execute([$row['name'], $row['surname'], $row['sex']]);
}
?>
for reference check this link https://phpdelusions.net/pdo_examples/insert

unable to update SQL table with php program

I have installed XAMPP and ensured that all the servers are running. I'm completely new to PHP and SQL
I configured a local database called test and a table called sensor.
I have added a user called arduino with a password.
pls ignore the comments
<?php
// Prepare variables for database connection
$dbusername = "arduino";
$dbpassword = "xxx";
$server = "localhost";
// Connect to your database
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
// Prepare the SQL statement
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
// mysql_query($sql);
?>
I want to use this set up to fetch data from arduino. Before connecting this set up to arduino, I wanted to ensure that this would be able to fetch data by passing http://localhost/write_data.php?value=100 to the browser. I was expecting that this would update the table with id, timestamp and value (of 100). It did not.
I had trouble with $dbconnect = mysql_pconnect($server, $dbusername, $dbpassword); and hence replaced that with $db = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
I also had trouble with mysql_query($sql);. So I have commented it out for now.
How can I get this to work? Where can I find easy to follow documentation for MySql replacements?
Updated Code based on answers
<?php
$dbusername = "arduino";
$dbpassword = "test";
$server = "localhost";
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
$stmt = $dbconnect->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
print "procedure returned $return_value\n";
?>
Brother checkout this example.. you have to bind get parameter in your query
Example:-
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM `$table` WHERE `$fieldname`=:id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
You are not executing the SQL statement in your code. Try executing the below implementation :
$db = new PDO('mysql:host=localhost;dbname=rfid_db;charset=utf8mb4', 'username', 'password');
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //optional
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //optional
$stmt = $db->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
Also for detailed study on PDO try referencing the documentation here http://php.net/manual/en/pdo.prepared-statements.php

What is wrong with my sql query? (PHP)

What is wrong with this code? Why can't I get the username from the members table in website database. Here's the screenshot of database information:
I am trying to make a function for it so that I can use it later. Here's the code:
<?php
function get_username($username){
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'website';
$con = mysqli_connect($host, $username, $password, $database);
$query = "SELECT * FROM members WHERE username = '{$username}'";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_array($result);
return $row['name'];
mysqli_close($con);
}
echo get_username('iamfaizahmed');
?>
Your username is overwritten in the function
$username = 'root'; // here
So no matter what you pass in the function argument it will always use
where username = 'root'
So use a different variable name
you are mixing between $username of the function and $username of your connect variable
change this
function get_username($username){
to
function get_username($user){
and do your query like that
$query = "SELECT * FROM members WHERE username = '$user'";
First thing, your $username variable.
You're passing it through the function and also using it for db connection.
Change your dbusername in the function as $dbusername
Second, the query. Keep it as:
$query = "SELECT * FROM members WHERE username = '$username'";
Now, once you're done with the basics, I recommend you to visit this link: Click Here
That should get your somewhere!

How do I display the value of a row?

I have five rows setup in a MySQLi database:
$title, $subtitle, $owner, $contactemail, and $footer.
Instead of writing out my websites title on EVERY .php page, I would like to use a function that will display the value of $title, $subtitle, etc.
This is what I have done so far:
index.php
<?php include 'config.php'; ?>
<?echo $title;?>
config.php
<?php
$mysql_hostname = 'localhost';
$mysql_username = 'root';
$mysql_dbname = 'toplist';
$mysql_password = '';
$dbh= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$query = "SELECT * FROM toplist_settings";
$title=['title'];
$subtitle=['subtitle'];
$owner=['owner'];
$contactemail=['contactemail'];
$footer=['footer'];
?>
But this is not working. When I use , etc. nothing shows up.
try this
$query = "SELECT * FROM toplist_settings";
$stmt = $dbh->query($query);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$title=$row['title'];
$subtitle=$row['subtitle'];
$owner=$row['owner'];
$contactemail=$row['contactemail'];
$footer=$row['footer'];
execute your query to get records
$query = $dbh->prepare("SELECT * FROM toplist_settings");
print_r( $query->execute());

New $_SESSION variable not created after query?

I'm trying to build a login process where, by using $_SESSION variables, the login credentials of the user are stored and used to show their relevant data from the database on screen (i.e. they will only see the school data that they work for).
<?php
session_start();
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
{
$host = "xxx";
$username = "xxx";
$password = "xxx";
$database_name = "xxx";
$table_name = "xxx";
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
$query = "SELECT Class FROM $table_name WHERE Initials = '".
$_SESSION['Initials']."' AND staff LIKE '%".$_SESSION['Surname']."'";
$result = mysql_query($query);
$class = mysql_fetch_array($result);
$count = mysql_num_rows($result);
if($count === NULL)
{
echo "ERROR";
}
else
{
$_SESSION['Class'] = $result;
echo "Class added to sessions";
}
}
?>
My initial problem where the query couldn't recognize the session variables was easily solved by adding the correct brackets for the if-statement. My next problem that has arisen here is that even though the query should be successfull (I don't receive an error message saying 'ERROR' when the $count is either FALSE or NULL) it's not creating the result array into a new session, because when I print the session array on a new page it's still only carrying over the 'Initials' and 'Surname' sessions.
What do I need to change to my query, or post-query process in order for that array (because it's bound to throw up multiple results) to be made into a new session?
Many thanks for the answers to my initial problem!
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
// code
}
u need { } brackets
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
$host = "xxxxx"; $username = "xxxxx"; $password = "xxxxx";
is
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
$host = "xxxxx";
}
$username = "xxxxx";
$password = "xxxxx";
I've found the answer - it turned out that I wasn't treating one of the session variables as a proper array and thus wouldn't load properly. I've added my script below so that people with similar problems in the future can use it as a reference point:
<?php
session_start();
// Server Details //
$host = "---";
$username = "---";
$password = "---";
$database_name = "---";
$table_name = "---";
// Connect Command //
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
// Query to call up the unique school name //
$query_school = mysql_query("SELECT DISTINCT School FROM $table_name
WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_school = mysql_result($query_school, 0);
// Query to call up the unique centre no //
$query_centreno = mysql_query("SELECT DISTINCT CentreNo FROM
$table_name WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_centreno = mysql_result($query_centreno, 0);
// The newly created sessions for school info //
$_SESSION['---'] = $result_school;
$_SESSION['---'] = $result_centreno;
// Query to call up the array of classes //
$query_class = mysql_query("SELECT Class FROM $table_name WHERE
Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$query_class__array = array();
while($row = mysql_fetch_assoc($query_class))
$query_class_array[] = $row;
$_SESSION['---'] = $query_class_array;
?>

Categories