Appropriate sql command to delete a row from table using form? - sql

I want to delete one row from one of my tables, based on a form -> "username".Let's assume, i have a log in page, where i write into the fields the apropriate username, and password based on a database which contains these values. After log in, i want to log out. And then I want to delete from the table the username and passwrod i used to sign in. How can i do it? Here's my code, it's unfortunately delete all the rows from the table. I have tried many ways... please help.
$sql="DELETE FROM login WHERE username='username'" ;
$result = mysqli_query($sqlconnection,$sql) or die...

assume that you receive the username value by a form by post and assign the value to a vars
$username = $_SESSION['login_user'];
then you can pass the value to you query this way
$sql="DELETE FROM login WHERE username='$username';" ;
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql="DELETE FROM login WHERE username='$username';" ;
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

Related

Converting SQL to Joomla Syntax (set and update)

Ok so basically I need to convert this regular sql statement to the syntax joomla uses via
https://api.joomla.org/11.4/Joomla-Platform/Database/JDatabaseQuery.html
here is my statement
SET #myunsubid = (
SELECT subid
FROM aqbi8_acymailing_subscriber s
WHERE s.email = 'email#email.co.nz'
);
SELECT #myunsubid;
UPDATE aqbi8_acymailing_listsub a
SET a.`status` = 1
WHERE a.subid = #myunsubid AND a.listid = 232
So id like it to be like
$db->set(#myunsubid = ( $db->select($db->quoteName('subid') )
$db->from($db->quoteName('aqbi8_acymailing_subscriber s') )
$db->where($db->quoteName('s.email') = 'email#email.co.nz')
)
$db->update($db->quoteName('aqbi8_acymailing_listsub a'))
$db->set($db->quoteName('a.status') = 1)
$db->where ($db->quoteName('a.subid') = #myunsubid AND $db->quoteName('a.listid') = 232 )
But this isnt quite right. please help!
I actually figured it out got it to work like this.
$db = &JDatabase::getInstance($option);
$query = $db->getQuery(true);
// make a variable for subID
$query->select($db->quoteName(array('subid')));
$query->from($db->quoteName('aqbi8_acymailing_subscriber'));
$query->where($db->quoteName('email') . " = '" . $email ."'");
$db->setQuery($query);
$db->execute();
$test = $db->loadObjectList();
print_r( $test );
$myid = $test[0]->subid;
$query->clear();
// // Create Database query
$fields = $db->quoteName('status') . ' = 1';
$conditions = array(
$db->quoteName('subid') . ' = ' . $myid,
$db->quoteName('listid') . ' = ' . $listid
);
// // update query
$query->update($db->quoteName('aqbi8_acymailing_listsub'))->set($fields)->where($conditions);
$db->setQuery($query);
$db->execute();
You don't need to make two trips to the database, you can write a subquery into your UPDATE's WHERE condition (no mysql variables or table aliases are necessary).
Raw Query:
UPDATE aqbi8_acymailing_listsub
SET status = 1
WHERE listid = 232
AND subid = (
SELECT subid
FROM aqbi8_acymailing_subscriber
WHERE `email` = 'email#email.co.nz'
)
Tested Code:
$db = JFactory::getDBO();
try {
$subquery = $db->getQuery(true)
->select('subid')
->from('#__acymailing_subscriber')
->where("email = 'email#email.co.nz'");
$query = $db->getQuery(true)
->update("#__acymailing_listsub")
->set("status = 1")
->where(["listid = 232", "personid = ($subquery)"]); // or make 2 where() calls
echo $query->dump(); // if you want to see; *during development ONLY
$db->setQuery($query);
$db->execute();
if ($affrows = $db->getAffectedRows()) {
JFactory::getApplication()->enqueueMessage("Updated. Rows affected: $affrows", 'success');
} else {
JFactory::getApplication()->enqueueMessage("Logic Error", 'error');
}
} catch (Exception $e) {
JFactory::getApplication()->enqueueMessage("Query Syntax Error: " . $e->getMessage(), 'error'); // never show getMessage() to public
}
It is not clear if any of your values are coming from users/untrusted sources, so be sure to follow good practices when writing variables into your queries -- like casting integers with (int) and calling $db->quote() on string values.
If you want to see a complex/convoluted UPDATE query with several other tables and techniques blended in, here is a comprehensive post: https://joomla.stackexchange.com/a/22916/12352
Please DON'T USE JDatabase Object to update Joomla tables, when there's an API available for the extension.
Whilst I appreciate the OP's question is pertaining to how to update the joomla database using the joomla database object (JDatabase), I propose a safer and more robust method, the "ACYMailing API".
"BUT WHY?", I hear you ask...
Good question!!!
There are 2 pitfalls in updating the joomla database directly - be it on the command-line, in a GUI such as MySQL Workbench or PHPMyAdmin, or even with the Joomla Database Object. Simply put, they both concern compatibility - 1. regarding third party integrations, and 2. concerning the future compatibility of your code. In a nutshell, whenever there's a an API for interacting with a component, I'd use it, over JDatabase every time to future proof your code, and ensure that all pre and post save, update, delete... ...move, and publish plugin events take care of your integrations, just as if you'd performed the action authentically.
To elaborate on these points a bit...
Most Joomla extensions (core and 3rd-party) make use of Joomla's powerful plugin architecture. By doing so, extensions can perform actions at key points in the application's life cycle. For example, after deleting a record from a table belonging to component1, delete related records from a table relating to compnent2. Therefore, one run's the risk of breaking the behaviour/functionality of the component in question - i.e. ACY Mailing, as in your case. Potentially, other core/3rd-party extensions that rely on ACY's data, that would otherwise, get updated through onAfterSave() or onAfterDelete() plugin events, as they will not get called.
There's a big risk that your code to break with future Joomla/ACY Mailing updates, if/when the table structure changes.
OK, so how do we use the API?
The following example code displays everything that you should need to update a subscription record. Each step explains the code, which for reference, is summarised in doc and inline comments in the code itself. To begin, navigate to the file where you are entering your code, then...
STEP BY STEP
STEP 1: Check the existence of ACY Mailing by attempting to include it's helper class, as follows. N.B. If the include_once() fails, you should see the echo statement, indicating that ACY Mailing IS NOT installed.
// load the ACY Mailing helper - bail out if not
if(!include_once(rtrim(JPATH_ADMINISTRATOR, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_acymailing' . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'helper.php')){
echo 'This code can not work without the AcyMailing Component';
return false;
}
STEP 2: Set-up your parameters by inputting values into the following 3 variables. See examples in code comments.
// array $lists An array of integer IDs (primary keys) of the lists you want the user to be subscribed to (can be empty).
// e.g. array(2,4,6)
$lists = array();
// array $unsubs An array of integer IDs (primary keys) of the lists you want the user to be un-subscribed from (can be empty).
// e.g. array(2,4,6)
$unsubs = array();
// string $userID Numeric Joomla User or user e-mail. For example: '42' or 'name#domain.com'
$userID = '';
STEP 3: Add the following code to find the ACY Mailing user, from the Joomla User ID/Email address passed in to the ->subid() method, and bail out if not found.
// instantiate the ACY Mailing Subscriber (user) Class
$user = acymailing_get('class.subscriber');
// find the ACY Mailing user id (subid) from the joomla ID or email address set in $userID
$subID = $user->subid($userID);
// No ACY Mailing user/subscriber?
if(empty($subID))
return; // bail out
STEP 4: Add the following code to check, and setup the data for any of the subscriptions/unsubscriptions you've configured to update ($lists and $unsubs arrays). If any found, they will be updated. If not found, return.
// create an array to store data in
$data = array();
// Set up new newsletter subscriptions from the $lists array()
if(!empty($lists)) foreach($lists as $listId)
$data[$listId] = array("status" => 1);
// Set up un-subscriptions from the $unsubs array()
if(!empty($unsubs)) foreach($unsubs as $listId)
$data[$listId] = array('status' => 0);
// no data, bail out...
if(empty($data))
return; //there is nothing to do...
// update the user's subscription records, creating/removing subscriptions/unsubsriptions accordingly
$user->saveSubscription($subID, $data);

How can I use sql data in header link?

I need to use a variable from SQL. I can print which I wrote the variable. But I can't use
it when it out of while query.
Here is the SQL:
if ($result = $mysqli->query("SELECT * FROM organize WHERE organize.nid=$nid"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
echo $row->nid;
echo $row->omid;
$id=$row->omid;
}
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
And the header under this scripts.
header("Refresh: 10;http://localhost/records.php?mid= $id ");
I know this is not right way. But I show you what I want. Need to use that 'omid' in header inseat of '$id'.
Finally I resolved it. This scripts like the above codes. I didn't understand why It didn't work. Maybe because I should not use
echo $row->nid;
echo $row->omid;
or
$id=$row->omid;
The right usage is as follows:
while ($row = $result->fetch_object())
{
$dd=$row->omid;
}
header("Refresh: 2;http://localhost/records.php?mid= $dd");

PDO INSERT & UPDATE query to different tables

I have a PDO SQL script which enables a user to complete a form which captures band information. It then posts this information to my database table called 'bands'. This works fine.
Simultaneously, I would like the script to update a different table called 'users' which has a column called 'num_bands' which needs to increase by a value of +1 if the user creates more than one band.
I have tried a number of methods, but none of them work. The script seems to be able to INSERT to the 'bands' table perfectly, but I cannot UPDATE the 'users' table. Here is the 'register_band' script:
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: ../index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to ../index.php");
}
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['username']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter a username.");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$query = "
INSERT INTO bands (
member_id,
username,
bandname,
bandhometown,
bandtype
) VALUES (
:member_id,
:username,
:bandname,
:bandhometown,
:bandtype
)
";
// Here we prepare our tokens for insertion into the SQL query. We do not
// store the original password; only the hashed version of it. We do store
// the salt (in its plaintext form; this is not a security risk).
$query_params = array(
':member_id' => $_POST['member_id'],
':username' => $_POST['username'],
':bandname' => $_POST['bandname'],
':bandhometown' => $_POST['bandhometown'],
':bandtype' => $_POST['bandtype']
);
try
{
// Execute the query to create the user
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
$query2 = "UPDATE users
SET num_bands = num_bands + 1
WHERE id = :member_id";
$stmt2 = $db->prepare($query2);
// This redirects the user to the private page after they register
header("Location: ../gig_view.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to ../gig_view.php");
}
?>
I'm running this in non-production mode at the moment, so the code is not 100%. How do I get the script to UPDATE the 'users' table?
$stmt->closeCursor();
$query2 = "UPDATE users
SET num_bands = num_bands + 1
WHERE id = :member_id";
$stmt2 = $db->prepare($query2);
$params = array(':member_id' => $_POST['member_id']);
$result = $stmt2->execute($params);
The code you have here is well documented, and explains how to use PDO statements, prepared queries and how to execute them with parameters.
Just follow the same pattern as you did with your SELECT, only the string of the query is meant to change here.

Magento - Module INSERT,UPDATE, DELETE, SELECT code

I created a module and want to used core write and read function to insert,update,delete or select database value with condition, how can I do it without using SQL?
Example:
$customer_id=123
Model=(referral/referral)
SELECT
$collection3 = Mage::getModel('referral/referral')->getCollection();
$collection3->addFieldToFilter('customer_id', array('eq' => $customer_id));
foreach($collection3 as $data1)
{
$ref_cust_id.= $data1->getData('referral_customer_id');
}
INSERT
$collection1= Mage::getModel('referral/referral');
$collection1->setData('customer_id',$customer_id)->save();
DELETE,UPDATE(with condition)=???
Suppose, I have a module named mynews.
Here follows the code to select, insert, update, and delete data from the news table.
INSERT DATA
$data contains array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.
$data = array('title'=>'hello there','content'=>'how are you? i am fine over here.','status'=>1);
$model = Mage::getModel('mynews/mynews')->setData($data);
try {
$insertId = $model->save()->getId();
echo "Data successfully inserted. Insert ID: ".$insertId;
} catch (Exception $e){
echo $e->getMessage();
}
SELECT DATA
$item->getData() prints array of data from ‘news’ table.
$item->getTitle() prints the only the title field.
Similarly, to print content, we need to write $item->getContent().
$model = Mage::getModel('mynews/mynews');
$collection = $model->getCollection();
foreach($collection as $item){
print_r($item->getData());
print_r($item->getTitle());
}
UPDATE DATA
$id is the database table row id to be updated.
$data contains array of data to be updated. The key of the array should be the database table’s field name and the value should be the value to be updated.
// $id = $this->getRequest()->getParam('id');
$id = 2;
$data = array('title'=>'hello test','content'=>'test how are you?','status'=>0);
$model = Mage::getModel('mynews/mynews')->load($id)->addData($data);
try {
$model->setId($id)->save();
echo "Data updated successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
DELETE DATA
$id is the database table row id to be deleted.
// $id = $this->getRequest()->getParam('id');
$id = 3;
$model = Mage::getModel('mynews/mynews');
try {
$model->setId($id)->delete();
echo "Data deleted successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
In this way you can perform select, insert, update and delete in your custom module and in any magento code.
Source: http://blog.chapagain.com.np/magento-how-to-select-insert-update-and-delete-data/
UPDATE is basically the combination of SELECT and INSERT. You load a collection, iterate over them setting the values as needed, then call ->save() on each model.
DELETE is handled directly via the ->delete() functon of models. So either load a single model or iterate over a SELECTed collection of them and call ->delete()
(Not that due to the iteration, this is not the 'fastest' way of doing these operations on collections (because each one is going to generate a new query, instead of a single query that handles multiple deletes at once), but the performance is fine for either small data sets/SELECTs (less than 1k?) or for things that you don't do very often (like importing or updating prices ok 10k products once per day).
FOR UPDATE
$new=$this->getRequest()->getParams();
$id=$new['id'];
$name=$new['name'];
$con=Mage::getModel('plugin/plugin')->load($id);
$con->setData('name',$name)->save();
echo "Update Success";
FOR DELETE
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('plugin/plugin');
$model->setId($id)->delete();
echo "Data deleted successfully.";
You can use select query like this also. its very easy.
$salesInvoiceCollection_sql = "SELECT `entity_id` , `increment_id`,`order_id`
FROM `sales_flat_invoice`
WHERE `erp_invoice_id` = 0
ORDER BY `entity_id`
DESC limit 1000";
$salesInvoiceCollection = Mage::getSingleton('core/resource')->getConnection('core_read')->fetchAll($salesInvoiceCollection_sql);
If you want to delete with condition based on collection you can use addFieldToFilter, addAttributeToFilter
$model = Mage::getModel('mynews/mynews')->getCollection();
try {
$model->addAttributeToFilter('status', array('eq' => 1));
$model->walk('delete');
echo "Data deleted successfully.";
} catch (Exception $e){
echo $e->getMessage();
}

Accessing Associative Indexes Produced by PDO FETCH_ASSOC

I fully admit must have a faulty understanding of the construction of an associative array.
The following login script will populate $userdata with an associative array consisting of $username's hashed password and salt as queried from the SQL Server database (Azure SQL to be specific). However, the portions of the code that are working on creating a hash of the supplied password and comparing against the hashed password found in the DB fail with errors indicating that $userdata[password] and $userdata[salt] are undefined.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// Connect to SQL Server
include '../../phpconfig/connectstrings.php';
try
{
$conn = new PDO ( "sqlsrv:server = $serverstringname; Database = $databasestringname", "$usernamestringname", "$passwordstringname");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION, );
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
catch(Exception $e)
{
die(var_dump($e));
}
//Query database for the hashed password and salt for the supplied username
if(!empty($_POST)) {
try
{
$sql_select = $conn->prepare("SELECT password, salt FROM logins WHERE username = '$username'");
$sql_select->execute();
}
catch(Exception $e)
{
die(var_dump($e));
}
//Fetch all of the remaining rows in the result set
$userdata = $sql_select->fetchAll(PDO::FETCH_ASSOC);
//check for a valid username
if(empty($userdata))
{
echo "User: $username was not found";
die;
}
//hash the queried salt and hash the supplied password
$hash = hash('sha256', $userdata['salt'] . hash('sha256', $password) );
//compare the hashed salted password supplied with that queried from database
if($hash = $userdata['password'])
{
echo "Welcome, $username!";
}
else
{
echo "Invalid password";
}
}
?>
While I don't doubt some of the code beyond fetching the array from $sql_select needs some debugging I can't get that far because $userdata appears to get all of the associative array data assigned to a single portion of the variable as indicated by the output of the following dumps:
var_dump($sql_select);
//output = object(PDOStatement)#2 (1) { ["queryString"]=> string(61) "SELECT password, salt FROM logins WHERE username = 'mrtactics'" }
list($a[0], $b[1]) = $userdata;
var_dump($a);
var_dump($b);
//output = array(1) { [0]=> array(2) { ["password"]=> string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a" ["salt"]=> string(3) "6e0" } } array(1) { [1]=> NULL }
var_dump($userdata["salt"]);
//output = NULL
var_dump($userdata['salt']);
//output = NULL
var_dump($userdata['password']);
//output = NULL
foreach ($userdata as $item => $value)
echo "$item: $value<br>";
//output = 0: Array
$password = $sql_select->fetchColumn(0);
$salt = $sql_select->fetchColumn(1);
var_dump($password);
var_dump($salt);
//output = string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a" bool(false)
The obvious workaround is to query a single value for the supplied username and pass each tot heir respective variables. However, this requires twice the necessary calls to the DB and I don't learn anything about how associative arrays are constructed and how I can get use the information stored within them.
I suspect I'm either fetching an object of the wrong construction for the method I am trying to retrieve from it or my syntax is just plain bad. I do intend to remain using PDO as opposed to sql_* commands.
EDIT: Let's make this more simple, then:
$userdatasql = $sql_select->fetchAll(PDO::FETCH_ASSOC);
$userdata['password']="f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a";
$userdata['salt']="6e0";
var_dump($userdata);
var_dump($userdatasql);
var_dump($userdata['password']);
var_dump($userdatasql['password']);
//Dump of $userdata = array(2) { ["password"]=> string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a" ["salt"]=> string(3) "6e0" }
//Dump of $userdatasql = array(1) { [0]=> array(2) { ["password"]=> string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a" ["salt"]=> string(3) "6e0" } }
Note the difference in the construction of these 2 arrays? I don't know exactly what it means which is why I'm here. If I were guessing it appears that the $userdatasql array contains an array within an array so calls must be indexed as such.
//Dump of $userdata['password'] = string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a"
//Dump of $userdatasql['password'] = NULL
MORE INFO:
echo (count($userdata));
echo (count($userdatasql));
//output = 2
//output = 1
echo (count($userdata, 1));
echo (count($userdatasql, 1));
//output = 2
//output = 3
This tells me that the array created by PDO FETCH_ASSOC is of a different construction than an array manually created but containing the same 2 pieces of data and the same 2 indexes.
Armed with this knowledge I modified my dump to include the 0 index location and suddenly the expected data was being output:
var_dump($userdatasql['0']['password']);
var_dump($userdatasql['0']['salt']);
//password dump = string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a"
//salt dump = string(3) "6e0"
Does this mean that I must reference all PDO FETCH ASSOC arrays by index?
I should think not since no code examples I find show this.
So, then, why is my PDO FETCH ASSOC array malformed?
Well, I have the "answer" in the sense that I can format the syntax to retrieve the necessary information from the associative array. I do not understand the difference between a manually created associative array and one created by PDO FETCH ASSOC nor what the implications are going to be later on when my arrays are significantly more complex than the one posed here.
But, here's the "answer":
The information stored in the associative array created by PDO FETCH ASSOC must be referenced by the numerical index THEN the associative index despite being an associative array not of the numerical type (because that makes loads of sense, right?) By including the numerical index prior to the associative index the value was correctly obtained.
$var[0][index] //retrieves correctly
$var[index] //does not unless the array happened to be manually constructed
And the final, for real answer, deduced after hours of studying other relevant code examples:
My code is performing as it is because I am using ->fetchAll as opposed to ->fetch. When I use simply ->fetch I no longer have to reference both numerical and associative indexes and can simply reference the associative index as expected for an associative array.
The corrected code syntax follows:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// Connect to SQL Server
include '../../phpconfig/connectstrings.php';
try
{
$conn = new PDO ( "sqlsrv:server = $serverstringname; Database = $databasestringname", "$usernamestringname", "$passwordstringname");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
catch(Exception $e)
{
die(var_dump($e));
}
//Query database for the hashed password and the salt for the supplied username
if(!empty($_POST)) {
try
{
$sql_select = "SELECT password, salt FROM logins WHERE username = ?";
$stmt = $conn->prepare($sql_select);
$stmt->bindValue(1, $username);
$stmt->execute();
}
catch(Exception $e)
{
die(var_dump($e));
}
//Fetch the result set into an associative array
$userdata = $stmt->fetch(PDO::FETCH_ASSOC);
if(empty($userdata))
{
echo "User: $username was not found";
die;
}
//hash the queried salt with a hash of the supplied password
$hash = hash('sha256', $userdata['salt'].hash('sha256', $password));
//compare the hashed salted password supplied with that queried from database
if($hash == $userdata['password'])
{
echo "Welcome, $username!";
}
else
{
echo "Invalid password";
//does the user wish to register> -> header('Location: register.php');
die;
}
}
?>