EDIT: Seems to be something with the database. We cant figure out what it is.
Im having a problem with storing data thats been put into the forms. I tested the query in MS SQL (we have to use that for school) but it doesnt seem to work once i put in my variables. So im guessing the problem comes from the variables. However im not sure about that because when i echo the $_POST variables it outputs strings like i want it to. But when i put it in the query it just wont store rit in my database. Would be great if someone could help me out with this.
HTML code:
<form action="registerSystem.php" method="post">
Email:
<input type="email" name="emailAdres" required> <br>
Naam:
<input type="text" name="naamGebruiker" required> <br>
Wachtwoord:
<input type="password" name="wachtwoordGebruiker" required> <br>
Herhaal wachtwoord:
<input type="password" name="bevestigWachtwoord" required> <br>
<input type="submit" value="Registreer">
</form>
Php code:
require "connect.php";
session_start();
GLOBAL $conn;
function createAccount(){
$email = $_POST['emailAdres'];
$username = $_POST['naamGebruiker'];
$wachtwoord = $_POST['wachtwoordGebruiker'];
GLOBAL $conn;
$hashed_pass = md5($wachtwoord);
$paypal = $email;
$subscription_start = date("Y:m:d");
$land = 'Nederland';
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name) "
."VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$conn->query($query);
}
if($_SERVER['REQUEST_METHOD'] === 'POST'){
//password check
if ($_POST['wachtwoordGebruiker'] == $_POST['bevestigWachtwoord']) {
createAccount();
header("location: loginSystem.php");
} else {
echo "De opgegeven wachtwoorden komen niet overeen!";
}
}?>
I have found where the problem is on your function.
The problem is here : VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
that null after :subscription_start is the problem, rather put a place holder in place then have a string that you will assign it value to null. then your query should work.
I'm not sure what datatype is subscription_end but I guess it should be date. and also use try catch block so that you can see when you have errors in your sql query. Also don't rush to reload the next page after running your query atleast but some delay on your header() so that you can print success message and see if its displaying then load next page
So this is how I updated your function.
<?php
require 'connect.php';
session_start();
GLOBAL $conn;
function createAccount()
{
$email = $_POST['emailAdres'];
$username = $_POST['naamGebruiker'];
$wachtwoord = $_POST['wachtwoordGebruiker'];
GLOBAL $conn;
$hashed_pass = md5($wachtwoord);
$paypal = $email;
$subscription_start = date("Y:m:d");
$land = 'Nederland';
$enddate = 'null';
try {
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name) " . "VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, :enddate, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$query->bindParam(':enddate', $enddate);
if ($query->execute()) {
echo "Done";
}
}
catch (PDOException $e) {
echo "error". $e->getMessage();
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//password check
if ($_POST['wachtwoordGebruiker'] == $_POST['bevestigWachtwoord']) {
createAccount();
header("refresh:5;url=loginSystem.php");
} else {
echo "De opgegeven wachtwoorden komen niet overeen!";
}
}
?>
Hope this helps.
NB: Don't use md5(); to encrypt your passwords its no longer safe,
rather use php functions password_hash() and password_verify()
they are available on php.net for you to read and understand them.
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name)"
." VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$query->execute();
What I've changed here is $conn->query($query); to $query->execute(). Because you're working with prepared statements, you need to call execute method of the object instance of prepared statement $query.
$conn->query($sql) is commonly used when only retrieving results with SELECT query which doesn't contain filtering conditions that receive data from user inputs.
For your information, as a best practice, wrap up the code with try catch blocks which helps you handle the errors.
try {
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name)"
." VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$query->execute();
} catch (PDOException $ex) {
echo $ex->getMessage(); // or die($ex->getMessage());
}
Before using try catch blocks, set the PDO's error reporting to exception:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Set this attribute as soon as you created the PDO object instance.
You can also set this attribute during the object instantiation through constructor like:
$conn = new PDO('mysql:host=localhost;dbname=demo', 'root', 'password', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
Hope it helps!
Related
I have been breaking my head around this html/php/mysqli thing and I can't get it to work. I used several echo statements to see what type of error I am facing but nothing shows up when I am trying to post data into my database.
I have used echo $_POST['name of input']; , print_r($_POST); and only on the 1st one I can see my post. So I think it is posting correctly, right?!
I for some strange reason can't find the problem in my code. I have searched for quiet some time on the web but with little to no result.
This is my HTML:
<html>
<head><title>Test2017</title></head>
<body>
<form action="insert.php" method="post">
<table width="400" border="0" cellspacing="10">
<tr>
<td>voornaam:</td>
<td><input type="text" name="voornaam"></td>
</tr>
<tr>
<td>roepnaam</td>
<td><input type="text" name="roepnaam"></td>
</tr>
<tr>
<td>tussenvoegsel</td>
<td><input type="text" name="tussenvoegsel"></td>
</tr>
<tr>
<td>achternaam</td>
<td><input type="text" name="achternaam"></td>
</tr>
<tr>
<td><input type="submit" value="registreren!"></td>
</tr>
</table>
</form>
</body>
</html>
and this my insert.php, and also at the VALUES i have tried "''",'' and "" but non of that worked.
<?php
$connect=mysqli_connect("localhost","root","usbw","test");
//check connection
if (mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
$voornaam= mysqli_real_escape_string($connect, $_POST['voornaam']);
$roepnaam= mysqli_real_escape_string($connect, $_POST['roepnaam']);
$tussenvoegsel= mysqli_real_escape_string($connect, $_POST['tussenvoegsel']);
$achternaam= mysqli_real_escape_string($connect, $_POST['achternaam']);
$sql="INSERT INTO user (voornaam,roepnaam,tussenvoegsel,achternaam) VALUES ('$voornaam','$roepnaam','$tussenvoegsel','$achternaam')";
if (!mysqli_query($connect,$sql)) {
die('Error: ' . mysqli_error($connect));
}
echo "1 record added";
mysqli_close($connect);
?>
You guys are my only help, because I am pulling my hair out for this.
Thank you in advance!
I have typed the HTML code first and I have pasted it everywhere else even in the database. So I would not have a problem like that. It is all lowercase.
I reformatted your original example to use a prepared statement, as this is safer for handling user generated input. I added a try catch around your code to attempt to raise visibility on whatever error you are running into
<?php
// ensure reporting for mysql is on.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
// Subbing out what you had for db connection to illustrate what each
// of those parameters should point to on your local db
$database = new mysqli('host', 'user', 'password', 'db_schema');
// guessing on whether these are strings.
$voornaam = filter_input(INPUT_POST, 'voornaam', FILTER_SANITIZE_STRING);
$roepnaam = filter_input(INPUT_POST, 'roepnaam', FILTER_SANITIZE_STRING);
$tussenvoegsel = filter_input(INPUT_POST, 'tussenvoegsel', FILTER_SANITIZE_STRING);
$achternaam = filter_input(INPUT_POST, 'achternaam', FILTER_SANITIZE_STRING);
// Formatting for readability, parameterized query
$query = "INSERT INTO user (
voornaam,
roepnaam,
tussenvoegsel,
achternaam
) VALUES ( ?, ?, ?, ?)";
// prepare query statement
$stmt = $database->prepare($query);
// bind parameters and types to statement
$stmt->bind_param('ssss', $voornaam, $roepnaam, $tussenvoegsel, $achternaam);
// execute
$stmt->execute();
echo 'Records added: ' . $stmt->affected_rows;
$stmt->close();
$database->close();
} catch (Exception $e) {
// basic print error to screen error handling, not ideal for
// anything other than testing :)
echo $e->getCode() . ' - ' . $e->getMessage();
}
Ok, we have probably totally confused you now, so try this
<?php
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$connect=mysqli_connect("localhost","root","usbw","test");
if (mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
// using 4 ? one for each column value in the query
$sql="INSERT INTO user
(voornaam,roepnaam,tussenvoegsel,achternaam)
VALUES (?,?,?,?)";
$stmt = $connect->prepare($sql);
// pass the actual data for each parameter, in order
// the 'ssss' in this case denotes that all 4 params are strings
// they can be s=string, i=integer,b=blob, d=decimal
$stmt->bind_param('ssss',
$_POST['voornaam'],
$_POST['roepnaam'],
$_POST['tussenvoegsel'],
$_POST['achternaam']
);
$result = $stmt->execute();
if ( $result ) {
echo "1 record added";
} else {
echo $connect->error;
}
}
?>
I have been trying to insert data into my database. I keep getting an error where it isn't recognising what is set. It thinks this is invalid: if (isset($_POST['user_email']) AND isset($_POST['user_choice'])) { so it skips and displays my echo with the values coming through.
Here is my HTML file:
<?php
require_once("../inc/config.php");
$emailAddress ="";
if(isset($_POST["user_email"])) {
$emailAddress = trim($_POST["user_email"]);
$newsletter = trim($_POST["emailLetter"]);
if($emailAddress != "") {
require_once(ROOT_PATH . "inc/images.php");
$results = capture_email($emailAddress, $newsletter);
}
var_dump($results);
exit();
}
?>
<footer id="footer-class">
<form id="footer-form" method="post" action="">
<fieldset>
<legend id="footer-legend">Sign up for...</legend>
<input type="radio" name="emailLetter" id="PC" value="PC" checked><label class="footerlabel" for="PC">Computer</label>
<input type="radio" name="emailLetter" id="Photo" value="Photo"><label class="footerlabel" for="Photo">Photo</label>
<legend id="footer-legend">Newsletter!</legend>
<input id="footer-email" type="email" name="user_email" placeholder="Enter your email address here!" required>
<button type="submit" id="footer-button">Subscribe</button>
</fieldset>
<p>I won't spam you. Promise</p>
</form>
</footer>
</body>
</html>
Here is my PHP function:
<?php
function capture_email($user_email, $user_choice) {
require(ROOT_PATH . "inc/database.php");
if (isset($_POST['$user_email']) AND isset($_POST['$user_choice'])) {
try {
$newsletter = $_POST["$user_choice"];
$email_address = $_POST["$user_email"];
$results = $db->prepare("INSERT INTO userinfo (Email, userOption) VALUES (?, ?)");
$results->bindparam(1, $email_address);
$results->bindparam(2, $newsletter);
$results->execute();
} catch (Exception $e) {
var_dump($e);
exit();
}
} else {
echo "Oops, something went wrong. Here is the user Email: " . $user_email . "<br>Here is the user choice: " . $user_choice;
exit();
}
}
Additional information: Config.php is a file containing variables for the database connection. images.php is a file where I store all my php functions.
Please let me know if you need anymore information.
Thanks
You no need to POST it. Already it is passed as an arguement.
if (isset($user_email) && isset($user_choice)) {
You have to change full code too.
<?php
function capture_email($user_email, $user_choice) {
require(ROOT_PATH . "inc/database.php");
if (isset($user_email) AND isset($user_choice) {
try {
$newsletter = $user_choice;
$email_address = $user_email;
$results = $db->prepare("INSERT INTO userinfo (Email, userOption) VALUES (?, ?)");
$results->bindparam(1, $email_address);
$results->bindparam(2, $newsletter);
$results->execute();
} catch (Exception $e) {
var_dump($e);
exit();
}
} else {
echo "Oops, something went wrong. Here is the user Email: " . $user_email . "<br>Here is the user choice: " . $user_choice;
exit();
}
}
I changed your function a little bit. you passing your post not your variable so it would cause a error. But this should work
function capture_email($user_email, $user_choice) {
require(ROOT_PATH . "inc/database.php");
/*
*You passing the POST, but your surpose to pass thru the var from your function.
*
**/
if (isset($user_email) AND isset($user_choice) {
try {
$newsletter = $user_choice;
$email_address = $user_email;
/**
**Also Sorted your issue out with your speech mark's
**
**/
$results = $db->prepare("INSERT INTO userinfo (Email, userOption) VALUES (?, ?)");
$results->bindparam(1, $email_address);
$results->bindparam(2, $newsletter);
$results->execute();
} catch (Exception $e) {
var_dump($e);
exit();
}
} else {
echo "Oops, something went wrong. Here is the user Email: " . $user_email . "<br>Here is the user choice: " . $user_choice;
exit();
}
Try this and re-run the code.
if(isset($_POST['user_email']) AND isset($_POST['user_choice'])) { ... }
You can use this condition like this :
if (isset($user_email) AND isset($user_choice)) {
try {
$newsletter = $user_choice;
$email_address = $user_email;
$results = $db->prepare("INSERT INTO userinfo (Email, userOption) VALUES (?, ?");
$results->bindparam(1, $email_address);
$results->bindparam(2, $newsletter);
$results->execute();
} catch (Exception $e) {
var_dump($e);
exit();
}
}
Because when you calling this function capture_email(), you have passed two trimed arguments.
there is syntax error :
if (isset($_POST['$user_email']) AND isset($_POST['$user_choice'])) {
replace with :
if (isset($_POST['user_email']) AND isset($_POST['user_choice'])) {
Update try block also :
try {
$newsletter = $_POST["user_choice"];
$email_address = $_POST["user_email"];
$results = $db->prepare("INSERT INTO userinfo (Email, userOption) VALUES (?, ?");
$results->bindparam(1, $email_address);
$results->bindparam(2, $newsletter);
$results->execute();
} catch (Exception $e) {
var_dump($e);
exit();
}
I have a problem when i try to check if email is alredy registered. can someone help? I have this error:
mysql_fetch_array(): supplied argument is not a valid MySQL result resource in line...
($record =mysql_fetch_array($result); )
<?php
$nome = $_REQUEST["nome"];
$cognome = $_REQUEST["cognome"];
$psw = $_REQUEST["psw"];
$email = $_REQUEST["email"];
$nikName = $_REQUEST["nikName"];
$conn = mysql_connect("host,name","userName","Password","databaseName");
if(!$conn) {
echo "connessione non satabilita";
} else {
if(!mysql_select_db("databaseName",$conn)) {
echo "database non trovato";
} else {
$sql = "select * from utenti where User='$email'"; //costruzione comando di ricerca
$result = mysql_query($sql,$conn); //assegnazione risultati
$record =mysql_fetch_array($result); //estrazione primo risultato
if(!$record) {
$sql = "INSERT INTO User (UserId, Nome, Cognome, Email, Username, Password, TimeStamp) VALUES (NULL,'$nome','$cognome','$email','$nikName','$psw', NULL)";
$result=mysql_query($sql);
if($result) {
echo "utente registrato correttamente";
} else {
//Error
echo "errore registrazione, riprovare più tardi";
}
echo "<br />";
echo "utente registrato";
} else {
echo "utente gia registrato";
}
}
}
?>
Before this gets out of hand.
$conn = mysql_connect("host,name","userName","Password","databaseName");
You're using 4 parameters rather than 3.
Sidenote: 4 parameters is mysqli_ syntax http://php.net/manual/en/function.mysqli-connect.php
Be careful though, those different MySQL APIs do not intermix. So you cannot have mysql_ with mysqli_ should you decide to change it to that.
The manual http://php.net/manual/en/function.mysql-connect.php states:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
the fourth is for something else.
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored.
So, just remove the 4th parameter.
Sidenote: This is questionable "host,name" (with the comma). Double check it as to what your host (if hosted) has provided you with. Most of the time, that should read as "localhost".
As stated, you're open to SQL injection.
Use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
As for the rest of your code:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Also add or die(mysql_error()) to mysql_query().
About you're wanting to check if an email exists; you may be better off using mysql_num_rows().
I.e.:
$sql = "select * from utenti where User='$email'";
$result = mysql_query($sql,$conn) or die(mysql_error($conn));
if(mysql_num_rows($result) > 0)
{...}
else {...}
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Also, this doesn't help you:
if(!mysql_select_db("databaseName",$conn)){
echo "database non trovato";
}
This does:
if(!mysql_select_db("databaseName",$conn)){
die ('Can\'t use the database : ' . mysql_error());
}
In order to get the real error, should there be one.
Reference:
http://php.net/manual/en/function.mysql-select-db.php
As mentioned above there is a syntax error with mysql_connect(); where you're trying to use invalid number of params. The best way is to make a config.php file and then use it whenever you need it. This is a basic connection code in PDO.
<?php
$host = "localhost";
$database = "yourdbnamehere";
$username = "yourusernamehere";
$password = "yourpasswordhere";
try {
$dbo = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
You will need a solution like this. But you must switch towards PDO or MySQLi to ensure that your code stays valid in long run as well as you will be able to write secure and stable code.
Go through these at first:
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/book.mysqli.php
An example code for you solving your current problem:
<?php
$nome = $_REQUEST["nome"];
$cognome = $_REQUEST["cognome"];
$psw = $_REQUEST["psw"];
$email = $_REQUEST["email"];
$nikName = $_REQUEST["nikName"];
try{
$pdo = new PDO('mysql:dbhost=hostname; dbname=databaseName', 'userName', 'Password');
} catch (PDOException $e) {
echo "Error connecting to database with error ".$e;
die();
}
// check for email
$sql = $pdo->prepare("select * from utenti where User= ?");
$sql->bindParam('1', $email);
$sql->execute();
/* if you aren't hashing the password,
then do it first
$psw = PASSWORD_HASH($psw, PASSWORD_DEFAULT);
*/
// Insert if email not registered
if($sql->rowCount() == 0) {
$insert = $pdo->prepare("INSERT INTO User (Nome,Cognome,Email,Username,Password) VALUES (?, ?, ?, ?, ?)");
$insert->bindParam('1', $nome);
$insert->bindParam('2', $cognome);
$insert->bindParam('3', $email);
$insert->bindParam('4', $nikName);
$insert->bindParam('5', $psw);
$insert->execute();
if($insert->rowCount() > 0) {
echo "utente registrato correttamente";
} else {
echo "errore registrazione, riprovare più tardi";
}
} else {
echo "utente gia registrato";
}
?>
i need your help. today i saw that if i put '(apostrophe) in some words then this text will not send to database. I tride to delete htmlentites or htmlspecialchars but not helped. please help me to fix this problem. thanks.
hier is profile.php
<?php
if(logged_in() === true){
if(empty($_POST['status']) === false && empty($_POST['user_status']) === false){
$status_data = array(
'body' => $_POST['status'],
'added_by' =>$user_data['username'],
'date_added' => date('Y-m-d H:i:s'),
'user_posted_to' => $_GET['username'],
'user_id' => $user_data['user_id']
);
update_status($id, $status_data, $user_id);
}
?>
<form class="forma" action="<? echo $username; ?>" method="post" accept-charset="utf8">
<div class="field">
<label for="Status" style="color: #7f7f7f; font-family: Cambria, Hoefler Text, Liberation Serif, Times, Times New Roman, serif;"></label>
<textarea rows="4" cols="50" name="status" placeholder="say something" id="status_area" charset="UTF-8" style=".value:black;"></textarea>
<div class='fild_bottom'>
<input name="user_status" type="submit" value="Post" id="button">
</div>
</div>
</form>
Here is function.php:
function update_status($id, $status_data, $user_id){
$query = #mysql_query('set character_set_results = "utf8"');
$user_id = mysql_query("SELECT * FROM users WHERE user_id = $user_id");
array_walk($status_data, 'array_sanitize');
$fields = '`' . implode('`,`', array_keys($status_data)) . '`';
$bank ='\'' . implode('\', \'', $status_data) . '\'';
mysql_query("INSERT INTO `status` ($fields) VALUES ($bank)");
}
function array_sanitize($item){
$item = htmlentities(strip_tags(mysql_real_escape_string($item)));
}
function sanitize($data){
return htmlspecialchars(strip_tags(mysql_real_escape_string($data)));
}
Please change your code to PDO. For an example, I'm refering to this SO Question
Change your function update_status to this (it's implied you've already made an db connection (object in $db)):
/* $user_id is unused, you should think about removing it */
function update_status($id, $status_data, $user_id) {
global $db;
$link = $db->prepare("INSERT INTO `status` (`body`, `added_by`, `date_added`, `user_posted_to`, `user_id`) VALUES (?, ?, ?, ?, ?)");
$link->bindvalue(1, $status_data['body']);
$link->bindvalue(2, $status_data['added_by']);
$link->bindvalue(3, $status_data['date_added']);
$link->bindvalue(4, $status_data['user_posted_to']);
$link->bindvalue(5, $status_data['user_id']);
$link->execute();
}
And remove the functions array_sanitize() and sanitize(), you won't need them anymore (Thanks to PDO and Prepared Statements). Also there is no need to use array_keys on the $status_data array, if the keys are always the same and known.
I don't know why you're selecting the user_id again in this function, since you're already getting it in $status_data.
edit: Throw this in a central file (you can either set the variables before try { or replace them with the correct values):
try {
$db = new PDO("mysql:host=".$host.";dbname=".$db.";charset=utf8", $user, $password);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //Stops emulating Prepared Statements
} catch(PDOException $e) {
die("Unable to connect. Error: ".$e->getMessage());
}
Another question regarding php and mysql... I'm wandering if it makes sense..
Basically above that code below.. is the form.. I want it to go through the validation with error counts.(code stated below) If counted error is 0, run that "INSERT INTO" code.. if counted error is 1 or more, show error and data not sent out.
But one thing though.. the code stated below doesn't actually "work" and doesnt give any errors :(
All comments really appreciated!
Thanks very much
<?php
global $pdo;
$pdo = new PDO('mysql:host=localhost;dbname=clubresults', 'root', '12345678');
#Set Error Mode to ERRMODE_EXCEPTION.
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
<<<<<<<FORM GOES HERE>>>>>>>>
<?php
function validatePattern(&$errors, $field_list, $field_name, $pattern)
{
if (!isset($field_list[$field_name]) || $field_list[$firld_name] == '')
$errors[$field_name] = 'Required';
else if (!preg_match($pattern, $field_list[$field_name]))
$errors[$field_name] = 'Invalid';
}
$errors = array();
validatePattern($errors, $_GET, ':firstname', '/^[A-Z][a-zA-Z -]+$/');
validatePattern($errors, $_GET, ':surname', '/^[A-Z][a-zA-Z -]+$/');
validatePattern($errors, $_GET, ':Player1', '/^[0-9a-zA-Z_]$/');
validatePattern($errors, $_GET, ':Player2', '/^[0-9a-zA-Z_]$/');
validatePattern($errors, $_GET, ':Player3', '/^[0-9a-zA-Z_]$/');
validatePattern($errors, $_GET, ':Player4', '/^[0-9a-zA-Z_]$/');
validatePattern($errors, $_GET, ':Player5', '/^[0-9a-zA-Z_]$/');
if (count($errors) >0){
echo "<font face='Verdana' size='2' color=red>$msg</font><br><input type='button' value='Retry' onClick='history.go(-1)'>";
}else{
if(("$stmt = $pdo->prepare('INSERT INTO members (firstname, surname, DD, MM, YYYY, email, Player1, Player2, Player3, Player4, Player5)
VALUES (:firstname, :surname, :DD, :MM, :YYYY, :email, :Player1, :Player2, :Player3, :Player4, :Player5)');
$stmt->bindParam(':firstname', $_GET['firstname']);
$stmt->bindParam(':surname', $_GET['surname']);
$stmt->bindParam(':DD', $_GET['DD']);
$stmt->bindParam(':MM', $_GET['MM']);
$stmt->bindParam(':YYYY', $_GET['YYYY']);
$stmt->bindParam(':email', $_GET['email']);
$stmt->bindParam(':Player1', $_GET['Player1']);
$stmt->bindParam(':Player2', $_GET['Player2']);
$stmt->bindParam(':Player3', $_GET['Player3']);
$stmt->bindParam(':Player4', $_GET['Player4']);
$stmt->bindParam(':Player5', $_GET['Player5']);
$stmt->execute();")){
echo "<font face='Verdana' size='2' color=green>Welcome, You have successfully signed up</font>";}
else{ echo "Database Problem, please contact Site admin";
}
?>
check with this for submit
if(isset($_POST['submit'])){
//get data and validation code comes here
}else{
//your form comes here
}
i hope this will work