Hello for a second time folks.
I asked a question recently about cleaning up some ugly code I had been cooking up and received the help I was asking for very quickly. Thanks for that!
original question thread is here: PHP - Search database and return results on the same page
I was quickly directed to use prepared statements in mysqli instead of what I had been doing to avoid SQL injections and such. I knew this advice would come my way, so it was no surprise. So I did some more digging and have re-written the original code accordingly. But now I have broken the form.
Anyone willing to take a look to see what I am missing? I am new at all of this and my searching on the internets has not helped me to debug this on my own.
<!DOCTYPE html>
<html>
<head>
<title>Client Search Results</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<form id="contact" action="" method="post">
<fieldset>
<h4>Search For Client</h4>
<input name="search" placeholder="Enter Name Here" type="text">
</fieldset>
<fieldset>
<button type="submit">Search</button>
</fieldset>
</form>
</div>
<div class='container'>
<form id='contact' action='edit.php' method='post'>
<fieldset>
<h4>Search Results</h4>
<select size="5" style="width:100%" name='id' >
<?php
// Include database communication info
include("../../comm/com.php");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Search
$search = "%{$_POST['search']}%";
$stmt = $db->prepare("SELECT client_id, firstname, lastname, city, state FROM client WHERE firstname LIKE ?");
$stmt->bind_param("s", $search);
$stmt->execute();
$stmt->store_result();
$numRows = $stmt->num_rows;
$stmt->bind_result($client_id, $firstname, $lastname, $city, $state);
if($result > 0) {
while ($stmt->fetch()) {
echo "<option value='$client_id'>$firstname $lastname - $city, $state</option>";
}
}
$stmt->close();
?>
</select>
</fieldset>
<fieldset>
<button type='submit' name='submit'>View Selection</button>
</fieldset>
</form>
<div>
</body>
</html>
After re-writing this code many times, and after receiving help from many different direction, this is the code that I settled on. Works like I want and seems to be solid.
<html>
<head>
<title>Client Search Results</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<form id="contact" action="" method="post">
<fieldset>
<h4>Search For Client</h4>
<input name="search" placeholder="Enter Name Here" type="text" autofocus>
</fieldset>
<fieldset>
<button type="submit">Search</button>
</fieldset>
</form>
</div>
<div class='container'>
<form id='contact' action='edit.php' method='post'>
<fieldset>
<h4>Search Results</h4>
<select size="5" style="width:100%" name='client_id' >
<?php
// Retrieve Search Term
if (isset($_POST['search'])) {
$search = "%{$_POST['search']}%";
}
// Include Connection Credentials
include("../../comm/com.php");
//Connection to Database
$link = mysqli_connect($servername, $username, $password, $dbname);
// Connection Error Check
if ($link->connect_errno) {
echo "Sorry, there seems to be a connection issue.";
exit;
}
// Prepared Statement For Database Search
if ($stmt = $link->prepare("SELECT client_id, firstname, lastname, city, state FROM client WHERE firstname LIKE ? OR lastname LIKE ?")) {
// Bind Search Variable
$stmt->bind_param('ss', $search, $search);
// Execute the Statement
$stmt->execute();
// Bind Variables to Prepared Statement
$stmt->bind_result($client_id, $firstname, $lastname, $city, $state);
// Fetch Values
while ($stmt->fetch()) {
// Display Results of Search
echo "<option value='$client_id'>$firstname $lastname - $city, $state</option>";
}
}
// Close Statment
$stmt->close();
// Disconnect from Database
mysqli_close($link);
?>
</select>
</fieldset>
<fieldset>
<button type='submit' name='submit'>View Selection</button>
</fieldset>
</form>
<div>
</body>
</html>
Related
I'm trying to make a form that posts the index.php input to my database table using index.php and connection.php. Also I'm trying to specify everything else to be in letter format except the phone number (puhelinnumero) in numeric format using bind_param, but it gives me this error:
Here is the index.php.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="lomake-container">
<form action="connection.php" method="POST">
<h2>Ilmoittautumis lomake</h2>
<div class="lomake-block">
<label for ="nimi">Etunimi</label>
<input type="text" name="etunimi" id="nimi" placeholder="Etunimi">
</div>
<div class="lomake-block">
<label for ="sukunimi">Sukunimi</label>
<input type="text" name="sukunimi" placeholder="Sukunimi">
</div>
<div class="lomake-block">
<label for="male">Mies</label>
<input type="radio" id="male" name="sukupuoli">
</div>
<div class="lomake-block">
<label for="female">Nainen</label>
<input type="radio" id="female" name="sukupuoli">
</div>
<div class="lomake-block">
<label for="other">Muu</label>
<input type="radio" id="other" name="sukupuoli">
</div>
<div class="lomake-block">
<label for ="sähköposti">Sähköposti</label>
<input type="text" name="sähköposti" id="sähköposti" placeholder="Sähköposti">
</div>
<div class="lomake-block">
<label for ="salasana">Salasana</label>
<input type="text" name="salasana" id="salasana" placeholder="Salasana">
</div>
<div>
<label for ="puhelinnumero">Puhelin numero</label>
<input type="text" name="puhelinnumero" id="puhelinnumero" placeholder="Puhelin num.">
</div>
<input type="submit" value="Lähetä">
</form>
</div>
</body>
</html>
Here is the connection.php
<?php
$etunimi = $_POST["etunimi"];
$sukunimi = $_POST["sukunimi"];
$sukupuoli = $_POST['sukupuoli'];
$sähköposti = $_POST['sähköposti'];
$salasana = $_POST['salasana'];
$puhelinnumero = $_POST['puhelinnumero'];
$servername = "localhost";
$username = "root";
$password = '';
$database = 'palvelu';
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else {
echo "Yhteys onnistui";
$stmt = $conn->prepare("insert into lomake($etunimi, $sukunimi, $sukupuoli, $sähköposti, $salasana, $puhelinnumero)
values(?, ?, ?, ?, ?, ?)");
}
$stmt->bind_param("sssssi",$etunimi, $sukunimi, $sukupuoli, $sähköposti, $salasana);
echo "onnistui jea";
$stmt->execute();
$stmt->close();
$conn->close();
?>
Here is the table:
You can't parameterise column names, but anyway I'm pretty sure that's not actually your intention, and you've possibly slightly misunderstood how to build an INSERT query. You need to specify the column names you want to insert into. The variable values you're currently trying to use in place of column names will be automatically assimilated into the query via the ? placeholders when MySQL receives the query.
Also you forgot to put the last value into the bind_param command.
Lastly your logic is a tiny bit flawed - if the connection fails, then your code will die. There's no need for the else. If it doesn't die, just carry on.
Try this instead:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Yhteys onnistui";
$stmt = $conn->prepare("insert into lomake(`nimi`, `sukunimi`, `gender`, `email`, `password`, `number`) values(?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssi",$etunimi, $sukunimi, $sukupuoli, $sähköposti, $salasana, $puhelinnumero);
echo "onnistui jea";
$stmt->execute();
$stmt->close();
$conn->close();
P.S.
Here is the MySQL documentation reference for INSERT: https://dev.mysql.com/doc/refman/8.0/en/insert.html
I am trying to send the data put into the input fields to my database and I cant seem to make it work out properly..
The ultimate goal is to put in the input fields into the database and show the inserted data in another window.
Here's my code
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// create a variable
$naam=$_POST['namen'];
$plaats=$_POST['plaatsen'];
$land=$_POST['landen'];
//Execute the query
mysqli_query($conn,"INSERT INTO phptoets(Namen,Plaatsen,Landen)
VALUES('$naam','$plaats','$land')");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="POST">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
Try this. It will help you. I've done few changes in your code.
- Add form to post the data on server
- Add database name in connection
- Add provincie field in form (because you are trying to get that in php)
- Use the same variable in query as declared at the time of connection
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "DATABASE";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// create a variable
$namen=$_POST['naam'];
$plaatsen=$_POST['plaats'];
$landen=$_POST['land'];
$provincie=$_POST['provincie'];
//Execute the query
mysqli_query($conn, "INSERT INTO employees1(naam,plaats,land,provincie) VALUES('$namen','$plaatsen','$landen','$provincie')");
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="POST" action="">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="text" name="provience" class="input_provience" placeholder="Provience"><br>
<input type="button" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
This is my solution:
You forgot to set database name and the names of your input fields where not equal to your $_POST names.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// create a variable
$naam=$_POST['naam'];
$plaats=$_POST['plaats'];
$land=$_POST['land'];
//Execute the query
mysqli_query($conn,"INSERT INTO phptoets(namen,plaatsen,landen)
VALUES('$naam','$plaats','$land')");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="post">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
<?php
// TESTS
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br>";
if(isset($_POST['submit']))
{
// create a variable
$a = (string)filter_input(INPUT_POST,'naam');
$b = (string)filter_input(INPUT_POST,'plaats');
$c = (string)filter_input(INPUT_POST,'land');
$d = (string)filter_input(INPUT_POST,'provincie');
echo("executing query <br>");
//Execute the query
if($a != null && $b != null && $c != null && $c != null)
{
$sql="INSERT INTO employees1 (naam,plaats,land,provincie) VALUES (?,?,?,?)";
echo("sql ".$sql. "<br>");
if($stmt = $conn->prepare($sql))
{
$stmt->bind_param("ssss",$a,$b,$c,$d);
$stmt->execute();
$stmt->close();
}
}
$sql = "SELECT naam, plaats, land, provincie FROM employees1";
if ($stmt = $conn->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($naam,$plaats,$land,$provincie);
while ($stmt->fetch())
{
printf("naam : %s, plaats: %s, land: %s, provincie: %s <br>",$naam,$plaats,$land,$provincie);
}
$stmt->close();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<form class="my_form" target="_self" enctype="multipart/form-data" method="post">
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="text" name="provincie" class="input_land" placeholder="Provincie"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</form>
</div>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
I will just name few things that I changed in your code, not mentioning syntax errors
you dont specify db_name in your sql connection
you dont use prepared statements nor any kind of input filtering
(note : my input filtering is very basic, read more about how to
filter inputs)
to address html form you need to create one and have submit input
type inside
I'm trying to build an html form and connecting it to a php file which is doing the query and insert the information to mysql database.
Here is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="/joomla_31/insert.php" method="post">
<label for="MGMT_IP">MGMT IP</label>
<input type="text" name="MGMT_IP" id="MGMT_IP">
</p>
<p>
<label for="Vendor">Vendor</label>
<input type="text" name="Vendor" id="Vendor">
</p>
<p>
<label for="Version">Version</label>
<input type="text" name="Version" id="Version">
</p>
<p>
<label for="GUI_User">GUI User</label>
<input type="text" name="GUI_User" id="GUI_User">
</p>
<p>
<label for="GUI_Pass">GUI Pass</label>
<input type="text" name="GUI_Pass" id="GUI_Pass">
</p>
<input type="submit" value="submit">
</form>
</body>
</html>
And Here is my insert.php file:
<?php
$link = mysqli_connect("localhost", "root", "", "mysql");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$MGMT_IP = mysqli_real_escape_string($link, $_REQUEST['MGMT IP']);
$Vendor = mysqli_real_escape_string($link, $_REQUEST['Vendor']);
$Version = mysqli_real_escape_string($link, $_REQUEST['Version']);
$GUI_User = mysqli_real_escape_string($link, $_REQUEST['GUI User']);
$GUI_Pass = mysqli_real_escape_string($link, $_REQUEST['GUI Pass']);
// attempt insert query execution
$sql = "INSERT INTO `cloud_team` (MGMT IP, Vendor, Version, GUI User, GUI Pass) VALUES (`$customer_number`, `$customer_name`, `$MGMT_IP`, `$Vendor`, `$Version`, `$GUI_User`, `$GUI_Pass`)";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
But every time I click on the submit button I get a blank page ...
It is like it is redirecting the correct file (http://x.x.x.x/joomla_31/insert.php) .. but nothing executed ...no error displayed .. only a blank page
Enable PHP error display to better debug your code. Look at this answer for more details.
I have two tables, members and games. In members is data such as member_id, first_name, last_name, etc.
What I'm trying to do is create a form for games, where the user can input the first and last names of the member who participated (in one string, not separately) and some PHP code queries this name, finds the corresponding id and stores this instead. Of course, member_id is a foreign key in games, but the users aren't going to know the member's id, they will only know their name.
If anyone could explain how I might go about doing this I would greatly appreciate it.
Form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
</head>
<body>
<form action="action.php" method="post">
<p>
<label for="date">Date:</label>
<input type="date" name="date" id="date">
</p>
<p>
<label for="duration">Duration:</label>
<input type="time" name="duration" id="duration">
</p>
<p>
<label for="member_id">Member Name:</label>
<input type="text" name="member_id" id="member_id">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
Action:
<?php
// database connection
include 'pdo_config.php';
try {
// new pdo connection
$conn = new PDO($dsn, $user, $pass, $opt);
// prepare statement and bind parameters
$stmt = $conn->prepare("INSERT INTO games (date, duration, member_id)
VALUES (:date, :duration, :member_id)");
$stmt->bindParam(':date', $date);
$stmt->bindParam(':duration', $duration);
$stmt->bindParam(':member_id', $member_id);
// post data
$date = $_POST['date'];
$duration = $_POST['duration'];
$member_id = $_POST['member_id'];
// execute statement
$stmt->execute();
// success or error message
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
This should work.
Ask the user to input the member name in the form instead of the member id. Then make a first query to the database to get the member id from the member name.
Have in mind that it's not a good idea to search the member id from its name, because you could have more than one member whit the same name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
</head>
<body>
<form action="action.php" method="post">
<p>
<label for="date">Date:</label>
<input type="date" name="date" id="date">
</p>
<p>
<label for="duration">Duration:</label>
<input type="time" name="duration" id="duration">
</p>
<p>
<label for="member_name">Member Name:</label>
<input type="text" name="member_name" id="member_name">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
// database connection
include 'pdo_config.php';
try {
// new pdo connection
$conn = new PDO($dsn, $user, $pass, $opt);
// post data
$date = $_POST['date'];
$duration = $_POST['duration'];
// Note that the explode only works well if user inputs one blank space to separate the name
// You can try to improve the separation method or better use two different inputs in the form
$nameArray = explode(" ", $_POST['member_name']);
$first_name = $nameArray[0];
$last_name = $nameArray[1];
$statement = $conn->prepare("SELECT member_id FROM members WHERE first_name = :first_name AND last_name = :last_name");
$statement->execute(array(':fisrt_name' => $first_name, ':last_name' => $last_name));
$row = $statement->fetch();
$member_id = $row['member_id'];
// prepare statement and bind parameters
$stmt = $conn->prepare("INSERT INTO games (date, duration, member_id)
VALUES (:date, :duration, :member_id)");
$stmt->bindParam(':date', $date);
$stmt->bindParam(':duration', $duration);
$stmt->bindParam(':member_id', $member_id);
// execute statement
$stmt->execute();
// success or error message
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
I have a question about my code. The problem is that when i say echo $collumB than he shows the student_city. that is in my database but i want that it shows the decrypted password. It just shows the wrong data
(there is an another page where i encrypt the password but i need the decrypted password echo'ed
<html>
<head>
<title>insert data in database using PDO(php data object)</title>
<link rel="stylesheet" type="text/css" href="style-login.css">
</head>
<body>
<div id="main">
<h1>Login using PDO</h1>
<div id="login">
<h2>Login</h2>
<hr/>
<form action="" method="post">
<label>Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Password :</label>
<input type="password" name="stu_ww" id="ww" required="required" placeholder="Please Enter Your Password"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
<?php
//require ("encrypt.php");
if(isset($_POST["submit"])){
$hostname='localhost';
$username='root';
$password='';
$pdo = "college";
$student_email = $_POST["stu_email"];
$encrypt_key = "4ldetn43t4aed0ho10smhd1l";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=college","root","$password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Query
$statement = $dbh->prepare("SELECT student_email, student_city, AES_DECRYPT(student_password, '$encrypt_key')
AS student_password FROM students WHERE student_email = :student_email ORDER BY student_email ASC");
// Assign and execute query
$statement->bindParam(':student_email', $student_email, PDO::PARAM_STR);
$statement->setFetchMode(PDO::FETCH_ASSOC);
$statement->execute();
// Get data
while($row = $statement->fetch()) {
echo "1 ,";
//$columnA_value = $row['student_city'];
$columnB_value = $row['student_password'];
}
echo "2 ,";
echo $columnB_value;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
</body>
</html>
SELECT student_email, student_city, CAST(AES_DECRYPT(student_password, '$encrypt_key') AS char(50)) AS student_password FROM students WHERE student_email = :student_email ORDER BY student_email ASC;
Try to explicitly cast it to string. You can change the '50' according to your requirement.
Also your echo is outside while loop, hence it will print only last record if there are more than 1 records.