delete user from table - mysql

I have this table where I want to delete user from. The users are in my database "login" where they have an id, username and password.
"Id" is the primary key, I want to delete the user where I click in my table
Hope you can help me out!
<?php
$account = '<font size="4">'.$account.'</font>';
$password1 = 'Password:';
$password1 = '<font size="4">'.$password1.'</font>';
//check db connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Take everything from table and fill in $result
$sql = "SELECT * FROM login";
$result = $conn->query($sql);
echo"<table border=4><tr><td>$account</td><td>$password1</td><td>Action</td></tr>";
if ($result->num_rows > 0) {
// Take all data
while($row = $result->fetch_assoc()) {
echo"<tr><td>".$row['username']."</td><td>".$row['password']."</td><td> edit | delete </td></tr>";
}
} else {
// nothing in DB is 0 results
echo "0 results";
}
echo"</table>";
$conn->close();
?>

<td> edit | <a href='baseURL/deleteUser.php&id=$userId'> delete</a> </td></tr>";
create a page deleteuser.php, get the id via $_GET['id'] and delete accordingly.
This is a very crude approach to delete users and the id goes via browser url. You can add forms here and delete text can be a submit button .. The id can be sent as hidden and obtained via $_POST

Related

MYSQL ON DUPLICATE KEY UPDATE not working as intended [duplicate]

This question already has answers here:
Insert into a MySQL table or update if exists
(12 answers)
Closed 2 years ago.
My app automatically checks when the customer logs in and only gives back one access_token and one shop values.
Below is the table with headings and a row of example data
access_token
shop
111111111
shop1
Sometimes a new customer installs the app and a new shop and access_token is created and I need to INSERT all new data in each column.
Other times the customer has re-installed the app so the shop exists but the access_token has changed and I need to update it.
How do I INSERT if none exist, but UPDATE if a value (shop) exists and another (access_token) doesn't when I am only given a single value of each?
I have attempted with ON DUPLICATE KEY UPDATE below where the shop is the same but the access_token has changed, but because I only get given one access_token to check when the customer logs in to the app it would just insert and not update.
INSERT INTO customers (access_token, shop)
VALUES(111, "shop1")
ON DUPLICATE KEY UPDATE access_token=111
I have attempted an example below where the shop is the same but the access_token has changed, however, I keep getting syntax errors. Please help, thank you.
SELECT EXISTS(SELECT shop FROM customers WHERE shop = 'shop1') AS sp,
NOT EXISTS (SELECT access_token FROM customers WHERE access_token = '{999999999}') AS tk
IF sp AND tk = 1
UPDATE customers
SET access_token='999999999'
WHERE shop = 'shop1';
ELSEIF NOT EXISTS (SELECT shop FROM customers WHERE shop = 'shop1') THEN
INSERT INTO customers (access_token, shop)
SELECT * FROM (SELECT '999999999', 'shop1') AS tmp;
END IF;
Are you using purely MySQL? I have made a signup and login page before as part of a web app and used Php to do this. I believe you can use Php for apks so I will write in Php, but you should be able to translate to your language with ease.
<?php
if (isset($_POST['signup-submit'])) { //this is so that the following can only be done on
the button press (name of it is signup-submit)
require 'dbh.inc.php';
$username = $_POST['Username'];
$email = $_POST['mail'];
$password = $_POST['pwd'];
$confirmpassword = $_POST['cpwd']; //this is all off the details of the user passed
through to be run through this script into the
database
if (empty($username) || empty($email) || empty($password) || empty($confirmpassword)) {
header("Location: ../index.php?error=emptyfields&uid=". $username. "&mail=". $email);
exit();
} //checking for empty fields
else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9 ]*$/", $username)) {
header("Location: ../index.php?error=invalidemail&uid");
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../index.php?error=invalidemailuid");
exit();
}
else if (!preg_match("/^[a-zA-Z0-9 ]*$/", $username)) {
header("Location: ../index.php?error=invaliduid&email=". $email);
exit();
}
else if ($password !== $confirmpassword) {
header("Location: ../index.php?error=checkpasswords&mail=".$email. "&uid=".$username);
exit();
} //checking all characters used are only that which you allow
else {
$sql = "SELECT uidusers FROM users WHERE uidusers=?";
$sqly = "SELECT emailusers FROM users WHERE emailusers=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
} //using prepared statements to insert user info
else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../index.php?error=usertaken&mail=". $email);
exit();
} //checking for existing details
if (!mysqli_stmt_prepare($stmt, $sqlx)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
if (!mysqli_stmt_prepare($stmt, $sqly)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck3 = mysqli_stmt_num_rows($stmt);
if ($resultCheck3 > 0) {
header("Location: ../index.php?error=emailtaken");
exit();
} //storing details
else {
$sql = "INSERT INTO users (uidusers, emailusers,
pwdusers, invcode) VALUES (?, ?, ?, ?) ";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else {
$hashedpwd = password_hash($password, PASSWORD_DEFAULT); //hashing passwords
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedpwd);
mysqli_stmt_execute($stmt);
header("Location: ../index.php?signup=success"); //all details stored successfully
As for your access token, I would suggest adding a function to run a uniqid() function along with another function to check for existing tokens so that duplicates aren't made ( I did this for another similar reason to yours) and then using similar code as above to write that in.
I'm not sure what your shop ID is for but I have options for 2 eventualities:
If it's just a sort of ID, auto increment it in the database
If it's to show which shop the person entered, use foreign keys to link the column to a parent table with all the shops listed and set the relationship to cascade. Then make a button to switch shops that will
A) send an update to the database, overwriting the child column and row of the user
B) redirect the user to the new shop
(I have no idea why the second half of the code is green, but if you remove my comments you should be good, though I'd advise you to write your own code so that you can see how it works and adapt it to your own project)

Provide Data from mysql using a search field in a form

i use a crm on a wordpress website. I'm trying to make a search field where a user can enter a number and with that number he/she should be able to see certain data from the database that is connected with the number that is entered.
What i got so far is:
<?php
$dbhost = 'localhost';
$dbuser = 'my user name';
$dbpass = 'my password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Kan geen connectie maken: ' . mysql_error());
}
$sql = 'SELECT lead_content FROM wp_wgbsupicrm_leads';
mysql_select_db('my database name');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Kan geen gegevens vinden: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['lead_content']} <br> ".
"--------------------------------<br>";
}
echo "Gegevens ontvangen\n";
mysql_close($conn);
?>
This will give me a result of:
resultaat:{"zoeknummer":"554477","komplex":"test
4","plaats":"84","versturen":null}
resultaat:{"zoeknummer":"556478","komplex":"test
3","plaats":"51","versturen":null}
resultaat:{"zoeknummer":"112255","komplex":"test
2","plaats":"12","versturen":null}
resultaat:{"zoeknummer":"110022","komplex":"Test
1","plaats":"1","versturen":null}
What i want is a search field where the "zoeknummer" is entered and the "komplex" & "plaats" are shown. the "versturen" isn't needed to be shown.
This is an image of the database where i need to get the information from:
enter image description here
To get this far i spended 1 and a half day.. I know i'm a total starter at this all, i have a basic html and css.. But i'm trying to learn more and hope with some assistance here i can get this to work, and in the mean time learn how it works.
Thanks in advance!
you should know how to use WHERE clause in your SQL query. this is mainly used for search purposes.
In your HTML form, give the textfield a name such as: name="$data"
Then in your SQL query:
$sql = "SELECT lead_content FROM wp_wgbsupicrm_leads' where lead_content='$data'";
Then the search will give you only the data you want from the text field you entered.

Why am i unable to insert a data in to data base

These are the codes for the page:
<?php
session_start();
if(isset($_SESSION['level'])){
if($_SESSION['level'] == 2 ){
require("../db/dbConn.php");
$submitted = isset($_POST['submit']);
if($submitted){
//check user's input
if(isset($_POST['issue_type'])){
$issue_type =$_POST['issue_type'];
}
else {
$issue_type = null;
echo '<p><font color="red">Please Select a Issue Type</font></p>';
}
if(isset($_POST['description'])){
$description=$_POST['description'];
}
else{
$description = null;
echo '<p><font color="red">You forgot to enter a description</font> </p>';
}
if(isset($_POST['reported_account_id'])){
$reported_account_id = $_POST['reported_account_id'];
}
else{
$reported_account_id = null;
echo '<p><font color="red">You forgot to enter your ID</font></p>';
}
if(isset($_POST['DateTimeCreated'])){
$DateTimeCreated=$_POST['DateTimeCreated'];
}
else{
$DateTimeCreated= null;
echo '<p><font color="red">You forgot to enter the date and time of the Issue </font></p>';
}
//Prepare the Insert Statement
$stmt = "INSERT INTO problem (issue_id, description, reported_account_id, DateTimeCreated) VALUES ('$issue_type', '$description','$reported_account_id','$DateTimeCreated')";
$result = mysqli_query($conn, $stmt);
$conn->close();
//TODO 5: Check result of executing insert statement and rows inserted. Print user's input if 1 row is inserted successfully,
// else print error message
if($result==true){
echo '<p><font color="green">The problem has been created. Thank you</font></p>';
echo '<p>Registration Successful Please Click Here';
} else {
echo "<p><font color=red><b>Data not saved. Please try again</b></font></p>";
echo '<p>Inserting Failed Please Click Here to Try Again';
}
}}
} else {
header("Location: ../index.php");
}
?>
I am not able to submit the insert the details from the form page into the database. That is the only issue that i am faced with. Please help me point out the errors that i made.
To Fix the issue, please replace
$stmt = "INSERT INTO problem (issue_id, description, reported_account_id, DateTimeCreated) VALUES ('$issue_type', '$description','$reported_account_id','$DateTimeCreated')";
With
$stmt = "INSERT INTO problem (issue_id, description, reported_account_id, DateTimeCreated) VALUES ('"+$issue_type+"', '"+$description+"','"+$reported_account_id+"','"+$DateTimeCreated+"')";

How to echo specific mysql data in specific places using php?

If the 'SELECT' statement is used to select data from a database then how do we echo specific rows to specific places on a page using php?
To explain this better - I am trying to SELECT * ALL FROM a table but to echo multiple rows to particular places on the html page using php.
So, imagine that my entire mark up and css has 20 thumbnails on a page and each thumbnail has data and an image that is unique to each thumbnail....do I have to replicate the below 20 times?
I am thinking that the best way to do this (which is probably completely wrong) is to use this statement
SELECT * FROM name_of_table WHERE ID = 4 >>> i.e. where I'd like that specific data echoed....
So, if I have 20 thumbnails do I do this 20 times?
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID = 4;")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['name'] . "</td> ";
Print "<th>Product:</th> <td>".$info['product_name'] . " </td></tr>";
}
Print "</table>";
?>
And, rinse and repeat but I change the below statement each time for each thumbnail (each thumbnail has unique data that comes from each row on the MySQL)
SELECT * FROM name_of_table WHERE ID = 4;
What is the best way of doing this?
Thanks!
Simple example.. First get the data with wanted ID:s. Create function for data request.
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID IN (2,3,4,5,6);")
or die(mysql_error());
// This holds all data rows
$data_array = array();
while($info = mysql_fetch_array( $data ))
$data_array[] = $data;
// Function for rendering data to html
function getItemHtml($id) {
$html = "";
foreach($data_array as $row) {
if ($row['ID'] == $id) {
$html = "<td>" . $row['title'] . "</td>";
// etc.. create item html here
break;
}
}
return $html;
}
// To create one item just call this with item id.
echo getItemHtml(4);
?>

Help with PHPExcel Library and mySQL data from a table

I have this script
$query = "SELECT id,last_name,first_name FROM users WHERE tmima_id='6'";
$result = #mysql_query($query);
while($row = mysql_fetch_array($result))
{
$i = 3;
$emp_id = $row['id'];
$cell = 'A'.$i;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cell, $row['last_name']. $row['first_name']);
$i++;
}
But in the .xls file it prints only one user. Why id doesnt print all of the users ? W
Thanks in advance.
I make the change you said with $sheet
$query = "SELECT id,last_name,first_name FROM users WHERE tmima_id='6'";
$result = #mysql_query($query);
while($row = mysql_fetch_array($result))
{
$i = 3;
$emp_id = $row['id'];
$cell = 'A'.$i;
$sheet->setCellValue($cell, $row['last_name']. $row['first_name']);
$i++;
}
But it still prints out only one record. And yes when i run the query in phpmyadmin it returns more than one record.
How can i print out data from mySql table.. What is going wrong ?
I am pretty sure it is because you are using a unique identifier (WHERE tmima_id='6'). It is only finding the results for that one unique identifier and displaying that. Hope this helps.
$i is being reset to row 3 every loop. Set $i=3; before the while loop, not inside it.