I'm building a simple app to send confirmation emails. I have a MySQL table with 4 columns: id, user_email, user_name and user_track. The form consists of a selectbox that shows all the user_email stored and two text inputs that should be autocompleted when an email is selected.
I have tried the following, but it just echo's all the entries for user_track and user_name.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, user_email, user_name, user_track FROM demo_data ORDER BY id DESC";
$option = '';
$artist = '';
$track = '';
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$option .= '<option value = "'.$row['user_email'].'">'.$row['user_email'].'</option>';
$track .= '<input type="text" name="track" required value = "'.$row['user_track'].'">';
$artist .= '<input type="text" name="artist" required value = "'.$row['user_name'].'">';
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Admin</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
<h1>Accepted demo</h1>
<form action="demo.php" method="post">
<select name="select">
<?php echo $option; ?>
</select><br><br>
<?php echo $track; ?><br><br>
<?php echo $artist; ?><br><br>
<input type="date" name="date" placeholder="Release Date" required>
<br><br>
<input style="margin-top:10px;" class="btn" type="submit" value="Send email">
</form>
</body>
</html>
<?php
$conn->close();
?>
update From
$sql = "SELECT id, user_email, user_name, user_track FROM demo_data ORDER BY id DESC";
To
$sql = "SELECT id, user_email, user_name, user_track FROM demo_data WHERE user_email='".$_POST['selected_user_email']."' ORDER BY id DESC";
where selected_user_email is the name of input field that is being posted
Related
creating a log in page using php and PDO however once I fill out the form with the correct username and password to log into the system and click log in, nothing changes except the boxes are now empty as if I never entered a username and password, can someone advise me as to what is going wrong?
this is the php code:
<?php
session_start();
$server = "127.0.0.1";
$dbusername = "root";
$dbpassword = "";
$db = "movie1";
$message = "";
try
{
$handle = new PDO("mysql:host=$server; dbname=$db", $dbusername, $dbpassword);
$handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
}
else
{
$query = "SELECT * FROM register WHERE username = :username AND password = :password";
$statement = $handle->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:login_success.php");
}
else
{
$message = 'Wrong Data';
}
}
}
}
catch(PDOException $error)
{
$message = $error->getMessage();
}
?>
and this is the html form to which it applies to:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>log in</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<form class="w3-container w3-card-4" action="login.php" method="post">
<h2 class="w3-text-black">Log in</h2>
<?php
if(isset($message))
{
echo '<label class "text-danger">'.$message.'</label>';
}
?>
<p>
<label class="w3-text-black"><b>username</b></label>
<input class="w3-input w3-border" name="username" type="text" placeholder="username"></p>
<p>
<label class="w3-text-black"><b>Password</b></label>
<input class="w3-input w3-border" name="password" type="text" placeholder="********"></p>
<p>
<input type="submit" name="login" class="w3-btn w3-black">Log in</input>
</p>
<p>
please ignore that passwords are not hashed, I will fix that later. the first image is what the log in form looks like with information entered and the next will be what happens after I click log in (pic one)1
pic two 2
I have made only minor changes to get your script working, see comments below. I think your login_success.php sends the authenticated user back to the login page.
<?php
/* my table in db named 'movie1':
CREATE TABLE `register` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL
);
INSERT INTO `register` (`username`, `password`) VALUES
('User1', '1111'),
('User2', '2222');
*/
session_start();
$server = "127.0.0.1";
$dbusername = "www"; //Changed
$dbpassword = "www"; //Changed
$db = "movie1";
$message = "";
try
{
$handle = new PDO("mysql:host=$server; dbname=$db", $dbusername, $dbpassword);
$handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
$message = '<label>All fields are required</label>';
else
{
$query = "SELECT * FROM register WHERE username = :username AND password = :password";
$statement = $handle->prepare($query);
$statement->execute(
array(
':username' => $_POST["username"], //Inserted colon here
':password' => $_POST["password"] //Inserted colon here
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:FileNotExistAndWillProduce404WhichMeansSuccess.php");//Target changed
}
else
$message = 'Wrong Data';
}
}
}
catch(PDOException $error)
{
$message = $error->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>log in</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<form class="w3-container w3-card-4" action="LoginTest.php" method="post"> <!-- action-target changed -->
<h2 class="w3-text-black">Log in</h2>
<?php
if($message>'') //was isset(), changed, because it contains at least an empty string
echo '<label class "text-danger">'.$message.'</label>';
?>
<p>
<label class="w3-text-black"><b>username</b></label>
<input class="w3-input w3-border" name="username" type="text" placeholder="username"></p>
<p>
<label class="w3-text-black"><b>Password</b></label>
<input class="w3-input w3-border" name="password" type="text" placeholder="********"></p>
<p>
<input type="submit" name="login" class="w3-btn w3-black">Log in</input>
</p>
</form></body></html>
This is my second topic tonight, but it's only because I can't really find any helpful information in regards to updating data in SQL using php. For some reason this won't update. If anyone has any suggestions that would be great :), again sorry for asking another question, I'm just eager to learn from my mistakes.
HTML Section:
<html>
<head>
<title>Update Data</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="editphpscript.php" method="post">
ID To Update: <input type="text" name="id" required><br><br>
New Status: <select name="status" required>
<option>Status</option>
<option value="Assigned">Assigned</option>
<option value="Pending">Pending</option>
<option value="No_Signal">No Signal</option>
<option value="Installed">Installed</option>
</select>
<input type="submit" name="update" value="Update Data">
</form>
</body>
</html>
PHP Section
<?php
// php code to Update data from mysql database Table
if(isset($_POST['update']))
{
$hostname = "";
$username = "";
$password = "";
$databaseName = "";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// get values form input text and number
$id = $_POST['id'];
$status = $_POST['status'];
// mysql query to Update data
$query = "UPDATE `leadlist` SET `status`='".$status." WHERE `id` = $id";
$result = mysqli_query($connect, $query){
($result){
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
mysqli_close($connect);
}
?>
For the past couple days, I have been trying to learn how to search an mysql database. So far I have the code below. for some reason it isn't searching and giving me results back. my database is named score and the table is all scores. Someone please help me with this.
It should be searching my database but it's coming up with no results. I have made sure everything is correct.
This file is searching.php
<?php
if (isset($_POST['search'])) {
$id = $_POST['id'];
$connect = mysqli_connect("localhost", "root", "root", "score");
$query = "SELECT `name` FROM `all_scores` WHERE `id` = $id LIMIT 1";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$name = $row['name'];
}
} else {
echo "Undifined ID";
$gameid = "";
}
mysqli_free_result($result);
mysqli_close($connect);
} else {
$gameid = "";
}
this is search.php
<!DOCTYPE html>
<html>
<head>
<title> PHP FIND DATA </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="searching.php" method="post">
Id:<input type="text" name="id"><br><br>
<input type="submit" name="search" value="Find">
</form>
</body>
</html>
To get the form values inside the php file you need to use $_POST. Here's an example using PDO. You're only retrieving one row so you don't need the while loop.
searching.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $conn->prepare("SELECT `name` FROM `all_scores` WHERE `id` = :id LIMIT 1");
$q->bindValue(':id', $_POST['id'], PDO::PARAM_STR, 50);
$q->execute();
if ($q->rowCount() > 0) {
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
Html:
<form action="searching.php" method="post">
Id:<input type="text" name="id"><br><br>
<input type="submit" name="search" value="Find">
</form>
Take some time look at several other examples
I would like to delete a row from my users table when the user clicks a button, the user needs to be logged in do delete their own account.
I have echo'd the $user_id which shows '4', which is the correct id for the logged in user, so user_id = $user_id
This is the page that I have which holds the button which I want to delete the users row in the database
<?php
include_once 'dbconfig.php';
if(!$user->is_loggedin())
{
$user->redirect('index.php');
}
$user_id = $_SESSION['user_session'];
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = $user_id ");
$stmt->execute();
}
$stmt = $DB_con->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt->execute(array(":user_id"=>$user_id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>Welcome - <?php print($userRow['user_email']); ?></title>
</head>
<body>
<div class="header">
<div class="right">
<label><i class="glyphicon glyphicon-log-out"></i> logout</label>
</div>
</div>
<div class="content">
Welcome <?php print($userRow['user_name']); ?> <br>
<?php print($userRow['team_name']);?><br>
Rank <?php print($userRow['user_rank']); ?> <br>
Players
Teams
<form action='teams.php' method='post'>
<input type='submit' name='leave' value='Delete Profile'/> </form>
<?php echo $user_id?>
</div>
</body>
</html>
I think your problem is your form action(teams.php) which will receive the post data.Your delete code is on the same file and logically $_POST['leave'] will never be set in this page.
Just try to remove your teams.php in your forms action attribute.
<form action='' method='post'>
<input type='submit' name='leave' value='Delete Profile'/> </form>
or in your teams.php file add your delete code
//Make sure you have started the session before using it
$user_id = $_SESSION['user_session'];
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = $user_id ");
$stmt->execute();
}
Another piece of advise is use parameterize query.
Example:
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = ? ");
$stmt-> bindParam(1,$user_id);
$stmt->execute();
}
<?php $servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} ?>
Delete
<?php if(isset($_GET['id'])){
$user_id = $_SESSION['user_session'];
$id=$_GET['id'];
if($id==$user_id){
$sql = "DELETE FROM Tablename WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
}?>
I have written this code to create a search form and get results from mysql table:
<?
$db_hostname = 'localhost';
$db_username = 'root';
$db_password = '';
$db_database = 'jatc_university_j32';
// Database Connection String
$con = mysql_connect($db_hostname, $db_username, $db_password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="FieldValue" /><br />
<input type="submit" value="Submit" />
</form>
<?
if (!empty($_REQUEST['FieldValue'])) {
$FieldValue = mysql_real_escape_string($_REQUEST['FieldValue']);
$result = mysqli_query($con, "SELECT Fieldvalue from #__rsform_submission_values WHERE FieldName = 'candidatname'");
while ($row = mysqli_fetch_array($result)) {
echo $row;
echo "<br>";
}
}
?>
</body>
</html>
In my database table I have FieldName: candidatname, candidatsurname and FieldValue: John, Wayne etc.
I want to search entering a name and return the other details for this candidate
Anyway when I run code nothing happens
Can you please check if I am doing wrong something because I get the same result in a lot of trials
1.Nothing happens beacuse you are using <? ?> for php, but you should use <?php ?>
2.Your form method is post then you should check variblae like this on form submit:
if (!isset($_POST['FieldValue']))
3. "SELECT Fieldvalue from #__rsform_submission_values WHERE FieldName = 'candidatname'"
instead of candidatename, give the value that you got from the form:
"SELECT Fieldvalue from #__rsform_submission_values WHERE FieldName = '".$FieldValue."'" <BR>
4. <input type="submit" value="Submit" /> add a name property to this like:
<input type="submit" value="Submit" name="Submit"/>
and it will work, i tested after applying these changes!
Try this:
<?php
$formpartone = <<<EODformpartone
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="{$_SERVER['PHP_SELF']}" method="get">
Search: <input type="text" name="FieldValue" value=""/><br />
<input type="submit" value="Submit" />
</form>
EODformpartone;
$formparttwo = <<<EODformparttwo
</body>
</html>
EODformparttwo;
if (!isset($_GET["FieldValue"]))
{
echo $formpartone;
echo $formparttwo;
}
ELSE {
function search_candidate(){
$host = "localhost";
$user = "root";
$password = "";
$database = "jatc_university_j32";
$searchstring = $_GET["FieldValue"];
$link = mysqli_connect($host, $user, $password, $database);
IF(!$link){
echo ('unable to connect to database');
}
ELSE {
$query = "SELECT candidatename, candidatesurname
FROM (
SELECT c.SubmissionID,
max(CASE WHEN c.FieldName='candidatename' THEN c.Fieldvalue ELSE 0 END) AS 'candidatename',
max(CASE WHEN c.FieldName='candidatesurname' THEN c.Fieldvalue ELSE 0 END) AS 'candidatesurname'
FROM mf2sn_rsform_submission_values as c
GROUP BY c.SubmissionID
) a
WHERE a.candidatename LIKE '".$searchstring."' OR a.candidatesurname LIKE '".$searchstring."'";
$result = mysqli_query($link, $query);
echo "<table>";
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<tr><td>".$row['candidatename']."</td><td>".$row['candidatesurname']."</td></tr>";
} echo "</table>";
}
mysqli_close($link);
}
echo $formpartone;
echo search_candidate();
echo $formparttwo;
}
?>
Sample table mysql
CREATE TABLE candidates
(
id int auto_increment primary key,
SubmissionID int,
FieldName varchar(20),
Fieldvalue varchar(30)
);
INSERT INTO candidates
(SubmissionID, FieldName, Fieldvalue)
VALUES
(1,'candidatename','Bob'),
(1,'candidatesurname', 'Smith'),
(2,'candidatename','Jack'),
(2,'candidatesurname', 'Doe');
SQLFiddle demo of the sample data
You should look into the validation and sanitation of the search string to avoid SQL injection. And what to do when no candidates are found with the name you inserted. However, I think for now it is important to test if everything works.