I've tried everything that I found on this community and other sites. But I'm still failing to complete my objective.
What I want to achieve:
On one page I have a input box with a button. When I fill in de ID number I want to get all the information out of mysql which is linked with this ID number....For some reason it doesn't work. Any tips or hints?
<?php
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxxx";
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT id, voornaam FROM sollicitatie_form WHERE id= "echo ($_POST['zoek'])"";
// $stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':voornaam', $voornaam, PDO::PARAM_STR);
$stmt->exec($sql);
$result = $stmt->fetchAll();
foreach ($result as $row){
echo "{$row['voornaam']}";
}
}
// use exec() because no results are returned
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" /></meta>
<head>
<title>Sollicitatie Formulier</title>
<link href="styletest.css" rel="stylesheet">
</head>
<body>
<div class="form">
<div class="tab-content">
<h1>Sollicitatie Formulier</h1>
<form method="post" enctype="multipart/form-data" >
<div class="top-row">
<div class="field-wrap">
<div class="field-wrap">
<input type="text" name="zoek" value="">
<input type="submit" name="submit" value="zoek">
</div> <!-- /field-wrap-->
</form>
</div><!-- /tab-content-->
</div> <!-- /form -->
</body>
</html>
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
if(isset($_POST['submit'])):
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, voornaam FROM sollicitatie_form WHERE id= :voornaam and city = :city");
// $stmt->bindParam(':id', $id, PDO::PARAM_STR);
//$stmt->bindParam(':voornaam', $voornaam, PDO::PARAM_STR);
$stmt->bindParam(':voornaam',$_POST['zoek'], PDO::PARAM_STR);
$stmt->bindParam(':city',$_POST['city'], PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row){
echo "{$row['voornaam']}";
}
}
// use exec() because no results are returned
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
endif;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" /></meta>
<head>
<title>Sollicitatie Formulier</title>
<link href="styletest.css" rel="stylesheet">
</head>
<body>
<div class="form">
<div class="tab-content">
<h1>Sollicitatie Formulier</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" >
<div class="top-row">
<div class="field-wrap">
<div class="field-wrap">
<input type="text" name="zoek" value="">
<input type="text" name="city" value="">
<input type="submit" name="submit" value="zoek">
</div> <!-- /field-wrap-->
</div>
</div>
</form>
</div><!-- /tab-content-->
</div> <!-- /form -->
</body>
</html>
If you want to fetch data you have to use SELECT statement not INSERT statement. Please check this answer hope it will helps you.
Edit
Please try again and check any error is showing or not.
FINAL EDIT
Now check it is running properly now, i just run it on my local server.
Updated with 2 parameters
You need to prepare the statement first, use a select (not insert), use a placeholder in the query, and execute the prepared object. Something like:
$stmt = $conn->prepare("select id, voornaam FROM sollicitatie_form WHERE id= :voornaam";
// $stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':voornaam', $voornaam, PDO::PARAM_STR);
$stmt->execute();
should do it. An alternative syntax I usually use is:
$stmt = $conn->prepare("select id, voornaam FROM sollicitatie_form WHERE id= ?";
$stmt->execute(array($voornaam)); //or array(':voornaam' =>$voornaam) if you prefer named placeholders
Also not echo is for outputting. You can concatenate or place a variable in to double quotes and then your PHP string will have the value.
Another example:
echo "{$row['voornaam']}"
can just be:
echo $row['voornaam'];
Related
I need to import the values of emailaddress and fullname from html into my SQL table.
Here is my HTML:
<!DOCTYPE html>
<head>
<title>Julian's Newsletter</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link href="newsletter.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
</head>
<body>
<h1>Newsletter</h1>
<form action="formsubmit.php" method="post">
<div class="container">
<h2>Subscribe to my Newsletter</h2>
<p>Subscribe to my newsletter to recieve recent news, a specialy curated product list, and the Product of the Month.</p>
</div>
<div class="container" style="background-color:white">
<input type="text" placeholder="Name" name="fullname" required>
<input type="text" placeholder="Email address" name="emailaddress" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Monthly Newsletter
</label>
</div>
<div class="container">
<input type="submit" value="Subscribe">
</div>
</form>
</body>
And here is my PHP so far. I am a beginner and I have very little knowledge of PHP.
<?php
$servername = "localhost";
$emailaddress = "emailaddress";
$fullname = "fullname";
$dbname = "email_windowsisslow_com";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $fullname, $emailaddress);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO emaillist (emailaddress, fullname)
VALUES ('', '')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
I am new to Stack Overflow and I do not assume that anyone will actually write the code for me. I need help understanding what is written, and how to write the code to perform the action I require of it.
I would suggest you must use prepared statements to avoid SQL injection.
$stmt = $conn->prepare("INSERT INTO emaillist (emailaddress, fullname)
VALUES (:emailaddress , :fullname)");
$stmt->bindParam(':emailaddress ', $emailaddress );
$stmt->bindParam(':fullname ', $fullname );
$stmt->execute();
In your PHP file change the two lines:
$emailaddress = "emailaddress";
$fullname = "fullname";
To
$emailaddress = $_POST["emailaddress"];
$fullname = $_POST["fullname"];
And add to your insert statement
$sql = "INSERT INTO emaillist (emailaddress, fullname) VALUES ({$emailaddress}, {$fullname})";
PHP only adding Numbers to MySQL in column of VARCHAR instead of texts
when using query directly in MySQL it works...but if I use $_POST from HTML, IT fails
I don't know the reason how it is getting failed. what is the problem here ?
<?php
$link=mysqli_connect("localhost","root","","home_ac");
if(mysqli_connect_error()) {
die("error in database");
}
$name =$_POST["name"];
$query = "INSERT INTO `test`(`number`, `name`) VALUES (NULL,$name)";
if(mysqli_query($link, $query)){
echo "done";
}
else {
echo "failed";
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<input type="text" placeholder="enter a name" name="name">
<input type="submit" value="add">
</form>
</body>
</html>
You need quotes around text
$query = "INSERT INTO `test`(`number`, `name`) VALUES (NULL,'$name')";
Please, think about prepared query. It solve quotes problem and protect from SQL injection.
You have to use PHP Prepared Statements or PHP Data Objects (PDO).
For example, using PDO:
<html>
<head>
<meta charset="utf-8">
<title> Example PDO Insert </title>
</head>
<body>
<form method="post" action="" name="myForm" id="myForm">
<input type="text" placeholder="Enter Your Name" name="name" required="required">
<input type="submit" name="submit" value="add">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "home_ac";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ( isset($_POST['submit']) && !empty($_POST['name']) ) {
# code...
$sql = "INSERT INTO test (number,name) VALUES (NULL,'$name')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
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.
Okay so my objective is to have people able to select there schedule. her is the code so far
<?php
//if form has been submitted process it
if(isset($_POST['submit'])){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "jesuitschedule";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'INSERT INTO schedule (Saturdaymorning, Saturdayafternoon, Sundaymorning, Sundayafternoon, weekday) VALUES (:Saturdaymorning, :Saturdayafternoon, :Sundaymorning, :Sundayafternoon, :weekday)';
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
//define page title
$title = 'schedule';
//include header template
require('layout/header.php');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>schedule</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form role="form" method="post" action="" autocomplete="off">
<h2>Please Select your schedule</h2>
<hr>
<div class="form-group">
<input type="checkbox" name="Saturdamorning" id="Satmor" class="form-control input-lg" placeholder="User Name" value="yes" tabindex="1">Saturday Morning <br>
</div>
<div class="form-group">
<input type="checkbox" name="Saturdayafternoon" id="Sataft" class="form-control input-lg" placeholder="S" value="yes" tabindex="2">Saturday Afternoon <br>
</div>
<div class="form-group">
<input type="checkbox" name="Sundaymorning" id="Sunmor" class="form-control input-lg" placeholder="S" value="yes" tabindex="3">Sunday afternoon <br>
</div>
<div class="form-group">
<input type="checkbox" name="Sundayafternoon" id="Sataft" class="form-control input-lg" placeholder="S" value="yes" tabindex="4">Sunday Morning <br>
</div>
<div class="form-group">
<input type="checkbox" name="weekday" id="email" class="form-control input-lg" placeholder="S" value="yes" tabindex="5">weekday <br>
</div>
<div class="row">
<div class="col-xs-6 col-md-6"><input type="submit" name="submit" value="Register" class="btn btn-primary btn-block btn-lg" tabindex="6"></div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
When I run my code all it works no errors but I when I check the table all I get is blank rows. The code adds a new sets of rows just doesn't add the data to them. I am trying to add either Yes, or to keep it blank if they do not select it. Any help would be great thanks.
As pointed out by Fred -ii-, you've not bound anything to your statement. Here's you code using a prepared statement. I've also commented the code as well to explain my position
if(isset($_POST['submit'])){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "jesuitschedule";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// You have a sql statement, but attempting to insert non-existant values. So you'll either
// wind up with an error, those values given in the statement inserted into the table,
// or just empty values.
//$sql = 'INSERT INTO schedule (Saturdaymorning, Saturdayafternoon, Sundaymorning, Sundayafternoon, weekday) VALUES (:Saturdaymorning, :Saturdayafternoon, :Sundaymorning, :Sundayafternoon, :weekday)';
// Create a prepared statement, let's you easily bind parameters
$stmt = $con->prepare(
'INSERT INTO schedule (
Saturdaymorning, Saturdayafternoon, Sundaymorning, Sundayafternoon, weekday
) VALUES (
:Saturdaymorning, :Saturdayafternoon, :Sundaymorning, :Sundayafternoon, :weekday
)';
);
// use exec() because no results are returned
//$conn->exec($sql); // You're executing a statement with no bound parameters
// You can use bindParam, but I find this method a tad easier
// Take the stmt created above, and bind the values to the parameters given
// in the statement, BUT, also execute. :)
$stmt->execute(array(
':Saturdaymorning' => 'value',
':Saturdayafternoon' => 'value',
':Sundaymorning' => 'value',
':Sundayafternoon' => 'value',
':weekday' => 'value'
));
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
If you'd like more info on this, take a look at the PDO page from the PHP site, which is where I pulled your fix: PHP: PDO - Manual