I currently have a website where the user can add profiles of people they know on a contacts page. I'm now trying to also let them delete specific profiles but I can't get it to work. Here's what I have so far.
Version 2.0 after feedback (now working):
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
profile = <input type = "text" name = "profile" required />
<input type = "submit" />
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "registration";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$prepped = $conn->prepare ('DELETE FROM users WHERE id = ?');
$prepped->bind_param ('i', $_POST["profile"]);
if ($prepped->execute()) {
// success
} else {
// failure
}
var_dump($_POST);
?>
The query you're executing is literally looking for an id "profile" in the database. Presumably the ID column is numeric so it can't possibly contain any rows with an id of "profile".
You need to pass the ID you want to delete in as a parameter to your query
$prepped = $conn->prepare ('DELETE FROM uses WHERE id = ?'); // The "?" is a placeholder that MySQL will replace with the specified parameter
$prepped->bind_param ('i', $_POST["profile"]); // 'i' indicates we're expecting an integer. See PHP docs for other options
if ($prepped->execute()) {
// The query executed without any errors (though you should also check how many rows were affected at this point to determine if anything was actually deleted)
} else {
// Failure
}
Additionally your form markup is incorrect and therefore probably not posting to the correct location.
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
Profile = <input type = "text" name = "profile" required />
<input type = "submit" />
</form>
Your query should look more like:
$query = sprintf("DELETE FROM uses WHERE id = '%s'", $profile);
or without sprintf():
$query = "DELETE FROM uses WHERE id = '" . $profile . "'";
EDIT after comments
$profile is a variable holding the string with the name / id / whatever you use to profile the user. From your form, you should define it in this way:
$profile = $conn->real_escape_string($_POST["profile"]);
of course before the query.
form action should be <?php echo $_SERVER['PHP_SELF']; ?>
see your code also.. what you are doing is passing the unknown $sql variable in if statement if ($conn->query($sql) === TRUE)
you have to pass $query variable defined above in this statement
Kindly replace your code with this code.. hope it will work for you :) goodluck
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
Profile = <input type = "text" name = "profile" required />
<input type = "submit" />
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "registration";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
///////////NEW CODE///////////
$profile_id = mysql_real_escape_string($_POST['profile']);
$query = "DELETE FROM users WHERE id= '".$profile_id."'";
if ($conn->query($query) === TRUE) {
echo "Profile deleted successfully";
} else {
echo "Error deleting profile: " . $conn->error;
}
//////////////////////////////
?>
Related
i want to store a data to the mysql database but if i press the submit button it display the php page.
form:
<div id="test">
<form action="demo.php" method="post">
please enter the number(1 to 100) : <input type="text" name="value">
<input type="submit">
</form>
</div>
demo.php
<?php
$value=$_POST['value'];
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
if ($conn->query($input) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Replace $input with $sql in the if statement:
From
if ($conn->query($input) == TRUE) {
To
if ($conn->query($sql) == TRUE) {
Note: Since you are storing $_POST['value'] in $value, you don't need to use $_POST['value'] in the query, instead make use of $value.
There is one correction:
Change
if ($conn->query($input) == TRUE) {
To:
if ($conn->query($sql) == TRUE) {
Along with that, following are suggestions:
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
This query is OK, is value of $_POST['value'] is integer, but, for strings, it will create SQL Syntax Error.
Please correct this to:
$sql = "INSERT INTO input VALUES ('".$_POST['value']."')";
Observe, enclosed semi colon.
2) You are inserting only one field value and not specifying fields. This means you table has only field. Normally we do not have tables with only one field.
Please specify field names:
$sql = "INSERT INTO input (field_one) VALUES (".$_POST['value'].")";
Get values like this
$value=$_REQUEST['value'];
change the query to
$sql = "INSERT INTO input VALUES ('$value')";
1st : Add name attribute to submit button name="submit"
<input name="submit" type="submit">
2nd : use isset like this if(isset($_POST['submit'])){ //rest of code here }
3rd : Try to use prepared statement or pdo to avoid sql injection
demo.php
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$stmt = $conn->prepare("INSERT INTO input(value) VALUES (?)");
$stmt->bind_param('s',$_POST['value']);
//The argument may be one of four types:
//i - integer
//d - double
//s - string
//b - BLOB
//change it by respectively
if ($stmt->execute() == TRUE && $stmt->affected_rows>0) {
echo "New record created successfully";
} else {
echo "Error: <br>" . $conn->error;
}
}
$conn->close();
?>
I want to input number in textbox in html and check if user with that ID exists in database Delovni_Cas if it exist echo Success otherwise Failed. I managed to get it to work without .$value. and just manually entering number like 1,2,3,...
<html>
<head>
<form method="get">
<INPUT TYPE = "Text" value="1" NAME = "IDU">
<INPUT TYPE = "Submit">
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "perkowich";
$conn = new mysqli($servername, $username, $password);
$value = $_POST['IDU'];
$query = mysqli_query($conn, "SELECT * FROM Delovni_Cas WHERE Zaposleni_ID_Osebe='".$value."'");
if(mysqli_num_rows($query) > 0) {
echo "Sucess";
} else {
echo "Failed";
}
$conn->close();
?>
<html>
<head>
</head>
</html>
You are using Get method in form and using $_POST in php, Please use $_GET instead of $_POST to get form value.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Php form for MySQL</title>
</head>
<body>
<form action="home.php" method="post">
<p>
<label for="table">Name your Table</label>
<input type="text" name="table" id="table">
</p>
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<button name="submit" type="submit" value="submit">Create Table</button>
</form>
if (isset($_POST['submit'])){
//enter database details
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$table = $_POST['table'];
// Create a MySQL table in the selected database
mysqli_query("CREATE TABLE $table (
firstname VARCHAR(30),
lastname VARCHAR(30),
email VARCHAR(50))") or die(mysql_error());
if ($conn->query($sql) === TRUE) {
echo "Table account created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
if(isset($_POST['firstname']) || ($_POST['lastname']) || ($_POST['email']))
{
$order="INSERT INTO $table (firstname,lastname,email) VALUES ('$firstname','$lastname','$email')";
$result = mysqli_query($order) or die (mysql_error());
}
mysqli_close($conn);
}
?>
</body>
</html>
I'm trying to allow the user to pick a name for the database and was stuck. I get an error
Access denied for user ''#'localhost' (using password: NO)
Picture of what I want:
I don't know what to do. Hope you can help. Thanks
The error you're getting means you're not providing valid credentials to connect to the database. Don't update them in your question, because these details should be private, but you need to change the code:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
to be the actual values. For instance, if your mysql username is 'tomi', the username line would look like this:
$username = "tomi";
You don't really have a database named 'database' do you? And if your actual password is 'password' you need to change it to something more secure.
You open a mysqli connection, and then use mysql_query to make a query, when it should be mysqli_query. mysql_* and mysqli_* are very different things, and you should never use mysql_* anymore. After changing this, check your authentication details. As long as you're on a private machine, maybe use var_dump() to look at them and make sure they're what you expect them to be. It looks like they might be getting passed into mysqli as empty strings. If your auth details are absolutely correct, double check that the given user in the database actually has the required privileges.
Editing my top answer with the full php code that I think will work for you:
<?php
if (isset($_POST['submit'])){
//enter database details
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "Failed to connect: (" . $conn->connect_error . ") ";
}
$table = $_POST['table'];
// SQL to Create a table in the selected database
$sql = "CREATE TABLE $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30),
lastname VARCHAR(30),
email VARCHAR(50))";
if ($conn->query($sql) === TRUE) {
echo "Table account created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Check connection
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
if(isset($_POST['firstname']) || isset($_POST['lastname']) || isset($_POST['email'])) {
$order="INSERT INTO $table (firstname,lastname,email) VALUES ('$firstname','$lastname','$email')";
if ($conn->query($order) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $order . "<br>" . $conn->error;
}
}
$conn->close();
}
?>
IMPORTANT:
1)
Make sure you enter the correct database details at the top of the php code. For example for me with xampp on windows it is:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
where I have previously created the database "database" manualy.
2) If you want to make sure in your later part of the code that all fields are NOT empty, you might prefer to use && (and) instead of || (or) for your conditions in the if. Currently it will run even as long as ANY of the fields are filled in, even if the rest of the fields are EMPTY.
Example:
if(isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email'])) {
instead of:
if(isset($_POST['firstname']) || isset($_POST['lastname']) || isset($_POST['email'])) {
I also highly suggest you check out the different ways to implement MySQLi with php; for example
Creating tables: http://www.w3schools.com/php/php_mysql_create_table.asp
Customer will complete a form and enter a pathway where they will want the CSV to be exported to. The pathway is entered using the top section of the php (below):
<form action="register.php" method="post">
Enter file pathway where CSV will be saved: <input type="text" name="username" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
</body>
I want to create a variable called pathway. At the moment I can get text entered into the correct row in the mysql database (I can get John printed in the database), but not the correct text that was entered into the form (i.e. $pathway).
I want to create a variable because after saving the pathway in the database i also want to use it in an export.php.
I am assuming i also need something like this:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$pathway = mysql_real_escape_string($_POST['pathway']);
// but i can't seem to piece it altogether.
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$table_users = $row['pathway'];
$pathway = "pathway";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('John')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
This shoud work, if not then check your usename and password...
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$pathway = $_POST['username']; username - is the name of your input.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('$pathway')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
your DB username is Null
Change $username = ""; to $username = "root";
Your input field name is username
change it to pathway for $_POST['pathway'] to work
<form action="register.php" method="post">
Enter file pathway where CSV will be saved:
<input type="text" name="pathway" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
First of all, you've got 'username' as the name of the field using for type a pathway, so rename it to 'pathway'.
I don't know if I understand you, but do you just want to read posted content?
Try something like:
$pathway = $_POST['pathway']
I strongly recommend to use object-oriented style with
$conn = new mysqli...
and then
mysqli->prepare(), mysqli->bind_param(), mysqli->execute()
With this you won't have to deal with mysqli_real_escape_string etc.
The problem: insert.php connects fine, but only inserts empty values ('') when I hit 'save' on the html form. The text I type, which I'm trying to insert, isn't saved. Somewhere a connection isn't being made and that data is lost but I can't figure out exactly where. Any help?
HTML insert form (collecting data for 2 parameters, 'user' and 'thread')
<form action="insert.php" method="post">
user: <input type="text" name="user"><br>
thread: <input type="text" name="thread"><br>
<input type="submit" value="Save">
</form>
PHP code to connect to SQL, insert inputted values
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "##.##.###";
$username = "harwoodjp";
$password = "~";
$dbname = "332";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (☒)<br/> " . $conn->connect_error);
}
echo "SQL (☑) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_connect($servername,$username,$password);
mysql_select_db("332project");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
try this
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
//create connection
$conn = mysql($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (☒)<br/> " . $conn->connect_error);
}
echo "SQL (☑) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_select_db("db");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
It might be because the default form posting method is GET.
Either change your $_POST to $_GET or add method="POST" to your form tag.