I'm trying to take a form that a user inputs from an HTML site and send the information to a SQL database. I am able to print out the variables after submission, so I know at the very least the variables are set properly. So I have to assume my code to send the content to the database is at fault here.
Here's the code:
//Taking variables from HTML input
if (isset($_POST['group'])) {
$group = $_POST['group'];
} else {
echo $error; return;
}
if (isset($_POST['game'])) {
$game = $_POST['game'];
} else {
echo $error; return;
}
if (isset($_POST['platform'])) {
$platform = $_POST['platform'];
} else {
echo $error; return;
}
if (isset($_POST['player'])) {
$player = $_POST['player'];
} else {
echo $error; return;
}
if (isset($_POST['play'])) {
$play = $_POST['play'];
} else {
echo $error; return;
}
if (isset($_POST['timezone'])) {
$timezone = $_POST['timezone'];
} else {
echo $error; return;
}
$error = 0;
//Retrieving Databse
try {
//userID and password is defined, just hiding it here
$dbh = new PDO("mysql:host=localhost;dbname=userID", "userID", "password");
} catch (Exception $ex) {
die("<p>($e->getMessage())</p></body></html>)");
}
//Inputting content into MySQL
$command = "INSERT INTO teams ( group, game, platform, player, play, timezone )
VALUES ( '$group','$game','$platform','$player','$play','$timezone')";
$stmt = $dbh -> prepare($command);
if ( ! $stmt->execute() ) {
$error = "<b>ERROR:</b> Could not record fields"; echo $error; return;
}
I'm not really sure where I've gone wrong, could be possible it's the tiniest thing or just something I've overlooked.
Thanks in advance for any help, guys!
This is how I did it for my Assignment:
Connecting to MySQL (notice that I dont have any mysql:host=):
$mysqli = new mysqli("localhost", "username", "pass", "database_name");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
Then in your code, when initializing variabels from POST, escape the strings. This will give you some protection against SQL-Injections:
$Name = $mysqli->real_escape_string($_POST["txtName"]);
$Street = $mysqli->real_escape_string($_POST["txtStreet"]);
$City = $mysqli->real_escape_string($_POST["txtCity"]);
Now, prepare a SQL code to insert your params:
$input = $mysqli->query("INSERT INTO customer (MembershipID, Name, Street, City, PostCode, Email, Password, DateJoin, Salt)
VALUES ('". $MembershipID."','".$Name."','".$Street."','". $City."','". $PostCode."','". $Email."','". $Password."','". $DateJoined."','". $Salt."')");
I hope it helps, Good Luck.
Related
I have tried multiple times to get this code to run and insert the data into a my database. No matter what I try I cannot figure out the problem. The php looks like this:
<?php
// Create connection
$conn = mysqli_connect("localhost","nmhsmusi_admin" , "********", "nmhsmusi_musicdb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['submit']))
{
$titleTag = $_POST['title'];
$composerTag = $_POST['composer'];
$unicodeTag = $_POST['unicode'];
$tempoTag = $_POST['tempo'];
$yearTag = $_POST['year-used'];
$languageTag = $_POST['language'];
$keyTag = $_POST['key-signature'];
$pianoTag = $_POST['piano'];
$temposelTag = $_POST['temposel'];
$partsTag = $_POST['parts'];
$run = mysqli_query($conn,"INSERT INTO musicdb (title, composer, unicode, temptxt, yearused, languages, pianokeys, piano, temposel, parts)
VALUES
(
'$titleTag', '$composerTag', '$unicodeTag', '$tempoTag', '$yearTag', '$languageTag', '$keyTag', '$pianoTag', '$temposelTag', '$partsTag'
)");
if ($run) {
echo "New record created successfully";
} else {
echo "failed";
}
mysqli_close($conn);
}
?>
Any help would be greatly appreciated
Why do you use mysqli? Has it already fallen into disuse?
PDO is now used.
Here's an example:
<?php
if (isset($_POST['submit'])) {
$titleTag = $_POST['title'];
$composerTag = $_POST['composer'];
$unicodeTag = $_POST['unicode'];
$tempoTag = $_POST['tempo'];
$yearTag = $_POST['year-used'];
$languageTag = $_POST['language'];
$keyTag = $_POST['key-signature'];
$pianoTag = $_POST['piano'];
$temposelTag = $_POST['temposel'];
$partsTag = $_POST['parts'];
try {
$pdo = new PDO(DSN,DBUSER,DBUSERPASSWD);
} catch (PDOException $e) {
echo "Failed to connect to Database: " . $e->getMessage() . "\n"; die();
}
$pdo->exec("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
$sql = "INSERT INTO musicdb (title, composer, unicode, temptxt, yearused, languages, pianokeys, piano, temposel, parts)
VALUES (:titleTag,:composerTag,:unicodeTag,:tempoTag,:yearTag,:languageTag,:keyTag,:pianoTag,:temposelTag,:partsTag)";
$query = $pdo->prepare("$sql");
$query->bindValue(':titleTag',$titleTag);
$query->bindValue(':composerTag',$composerTag);
$query->bindValue(':unicodeTag',$unicodeTag);
$query->bindValue(':tempoTag',$tempoTag);
$query->bindValue(':yearTag',$yearTag);
$query->bindValue(':languageTag',$languageTag);
$query->bindValue(':keyTag',$keyTag);
$query->bindValue(':pianoTag',$pianoTag);
$query->bindValue(':temposelTag',$temposelTag);
$query->bindValue(':partsTag',$partsTag);
$query->execute();
if($query->rowCount() > 0){
echo "New record created successfully!";
} else {
echo "Error!";
}
}
?>
Of course you need to filter everything that comes from the form with regular expressions. Easy thing to do!
Once the regular expressions have analyzed everything you need to convert everything to htmlentities to avoid malicious code:
The regular expression "/([a-zÀ-ÿ0-9\s]+)/i" below allows only letters with or without accents, numbers, and spaces:
<?php
preg_match('/([a-zÀ-ÿ0-9\s]+)/i', $_POST['any_field_form'], $output);
if((isset($output[1]) == true) and ($output[1] != null)) {
//Convert everything to htmlentities to avoid malicious code
$get_the_data = htmlentities($output[1], ENT_QUOTES, 'UTF-8', false);
} else {
$get_the_data = null;
}
?>
With this you avoid problems with forms. Of course for each form field you will have to do a specific regular expression. But that makes your code smarter.
Sorry if there are any errors in the text. I know how to read in English, but I do not know how to write so I used a translator for that.
But that's it, boy!
Trying to make the switch over to OOP PHP as opposed to my current approach of having a whole load of PHP code in all of my pages.
I've thrown something together which takes a post title, content and status and stores it in a simple database.
I just want to know if I have the right idea or if I'm way off - is it worth me carrying on taking this approach on it?
<?php
$conn = new mysqli('127.0.0.1','root','','admin');
class post {
private $title;
private $content;
private $status;
private $errors;
private $check;
function __construct(){
if(isset($_POST) && !empty($_POST)){
if(empty($_POST['title'])){
$this->errors[] = "Title is required";
}
if(empty($_POST['content'])){
$this->errors[] = "Content is required";
}
if(empty($_POST['status'])){
$this->errors[] = "Status is required";
}
if(empty($this->errors)){
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->status = $_POST['status'];
$this->check = true;
} else {
echo "<pre>";
var_dump($this->errors);
echo "</pre>";
}
}
}
function submit(){
if($this->check){
global $conn;
if($conn->connect_error){
die("Connection error: " . $conn->connect_error);
};
$stmt = $conn->prepare("INSERT INTO posts (title, content, status) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $this->title, $this->content, $this->status);
if($stmt->execute()){
echo "Post added succesfully";
} else {
echo "<pre>";
var_dump($stmt);
echo "</pre>";
}
};
}
};
?>
so I have searched this problem and found similar ones, but I'm not sure of how to translate their solutions into mine - mainly because I'm a noob in PHP. I'm working on it. Bear with me. I appreciate the help!
Right now, I am trying to make it so my form will not allow duplicate entries for the email column in phpmysql. So far, I went into the structure tab there, and made it unique. Pretty much viola. However, I would like the error message to display on the same page when the form is submitted, instead of reloading it and giving the message. Also, I would like to customize the message. Seeing as its a phpmysql related error, I'm not sure if I would do that with PHP coding, or somewhere in there.
Thanks guys. I appreciate the help.
<?php
function checkField($v){
return (isset($v) && $v === false) ? true: false;
}
function startMysql(){
$con=mysqli_connect("localhost", "shiftedr_admin", "passwerd", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return null;
}
return $con;
}
// function closeMySql($connection){
// mysqli_close($connection);
// }
function formcheck(){
$con=mysqli_connect("localhost", "shiftedr_admin", "shithead1", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
if (isset($_POST['submitted'])){
$form = null;
if (empty($_POST['fullname'])){
$form['fullnameflag'] = false;
}
if (empty($_POST['email'])){
$form['emailflag'] = false;
}
if (empty($_POST['password'])){
$form['passwordflag'] = false;
}
if (empty($_POST['pwc'])){
$form['pwcflag'] = false;
}
if (empty($_POST['userbday'])){
$form['userbday'] = false;
}
if (empty($_POST['gender'])){
$form['genderflag'] = false;
}
if ($_POST['password'] != $_POST['pwc']){
$form['fixpasswordconfirm'] = false;
}
/*$query = mysql_query ("SELECT * FROM users2 WHERE email = '". Email'" ."'");
if (mysql_num_rows($query) > 0)
{
echo 'Email Address is Already In Use.';
}*/
if (empty($form)) { // all fields correct at this point, do database stuff
$sql="INSERT INTO Users2 (fullname, Email, Password, userbday, Gender) VALUES ('".$_POST['fullname']."','".$_POST['email']."','".$_POST['password']."','".$_POST['userbday']."','".$_POST['gender']."')";
if (!mysqli_query($con,$sql)){
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
}
mysqli_close($con);
return $form;
}
}
//// / include("myfunctions.php");
?>
I am guessing you have two pages - myform.php and process.php or something similar so try doing this
<?php
$error = null;
if( isset( $_POST['submitted'] ) ) // Same as your check is submitting if
{
// Below is an example fail
if( empty( $_POST['fullname'] ) ) $error = 1;
// So for the email address failing you would put
if( mysql_num_rows($query) > 0 ) $error = 2;
if(! $error )
{
// all good no errors here so do database stuff....
}
else
{
header("Location: form.php?error=$error"); // return the error code to previous page
}
}
?>
Were one could be an empty field or could be fullname is empty and two is used email address or something similar and on your myform.php page have
<?php
if( isset( $_GET['error'] ) )
{
switch ( $_GET['error'] )
{
case 1 : echo "One of the fields is empty"; break;
case 2 : echo "Your email address has already been used"; break;
default : echo "Unknown error occured";
}
}
?>
Hi I am facing a unique issue with my PHP script.Here is my code. After writeToDB() is executed I dont see the echo ("<script> top.location.href=www.facebook.com</script>");
Can someone let me know why my script stops executing after writing to db?
<?php
function writeToDB($access_token,$uid,$username,$birthday,$gender,$age)
{
/* Database Connection */
$user = "xxxx";
$password = "xxxx";
$host = "xxxxxxxxxxxxxxxxxx";
//connect to database, where tsnames.ora is setup
$connect_obj = oci_connect($user, $password, $host);
if ($connect_obj) {
error_log("connected okay");
} else {
$err = OCIError();
echo "Oracle connection error " . $err[text];
return;
}
$select_query = "SELECT USER_ID FROM FBTABLE WHERE USER_ID= '$uid'";
$select_sql_stmt = oci_parse($connect_obj, $select_query);
//execute statement
try {
$r = oci_execute($select_sql_stmt, OCI_DEFAULT);
if (!$r) {
$p = oci_error($select_sql_stmt);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
$user_id_in_db = null;
while (oci_fetch($select_sql_stmt)) {
$user_id_in_db = oci_result($select_sql_stmt, 'USER_ID');
}
// User already exists in db so update instead of insert
if ($user_id_in_db != null) {
$query ="UPDATE FBTABLE SET ACCESS_TOKEN='$access_token' WHERE USER_ID='$uid'";
} else {
$query = "INSERT INTO FBTABLE(ACCESS_TOKEN, USER_ID,USER_NAME,BIRTHDAY,GENDER,AGE)
VALUES
('$access_token','$uid','$username','$birthday','$gender','$age')";
}
//create sql statement
$sql_statement = oci_parse($connect_obj, $query);
//execute statement
try {
$r = oci_execute($sql_statement, OCI_DEFAULT);
if (!$r) {
$p = oci_error($sql_statement);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
//Commit transaction
$committed = oci_commit($connect_obj);
//Test whether commit was successful. If error occurred, return error message
if (!$committed) {
$error = oci_error($conn);
echo 'Commit failed. Oracle reports: ' . $error['message'];
}
//close the connection
$oci_free_statement($sql_statement);
if (oci_close($connect_obj)) {
echo " oci connection not closed!!!";
}
//close the connection
$oci_free_statement($sql_statement);
}
?>
<html>
<body>
<?php
$access_token = $_GET['access_token'];
$uid = $_GET['uid'];
$username = $_GET['username'];
$birthday = $_GET['birthday'];
$gender = $_GET['gender'];
$age = $_GET['age'];
echo $username;
writeToDB($access_token,$uid,$username,$birthday,$gender,$age);
echo ("<script> top.location.href=www.facebook.com</script>");
?>
</body>
</html>
i think error is in $oci_free_statement($sql_statement); must be oci_free_statement($sql_statement); extra $ before oci_free_statement
http://php.net/manual/en/function.oci-free-statement.php
no any error show because of error_display is off
Your JavaScript code should be
echo ("<script> top.location.href='http://www.facebook.com';</script>");
It's happen because writeToDB() causes error. You don't see this error because error_display is off or error_reporting = 0
Also maybe you didn't install OCI8. So when you call oci_connect it will cause error.
Thanks.
you are not using quotes around the string:
www.facebook.com should be 'www.facebook.com'
I made this kind of point system, where users can spend their points. The users points do get deducted. I didn't include alot of the variables, but they are all okay. The problem occurs at return($success) and return($error_message).
Here is the code:
function died($error) {
header("Location: error_points_on.php?error=" . $error);
die();
}
function success($success) {
header("Location: success_points_on.php?success=" . $success);
die();
}
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
function product($price,$points, $name, $uname, $error_message, $success_message) {
$user_name = "cencord";
$pass_word = "cencord";
$database = "cencord";
$server = "cencord";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) { // connect to DB
$uname = quote_smart($uname, $db_handle);
$SQL = mysql_query("SELECT points FROM members WHERE username=$uname");
$points = mysql_fetch_row($SQL);
$points = $points[0]; // make it a variable rather then an array
if ($points >= $price) {
$points = $points-$price; // fjern points
$points = quote_smart($points, $db_handle);
mysql_query("UPDATE members SET points=$points WHERE username = $uname");
$success_message .= "The " . $name . " has been mailed to your E-mail, please allow 5 minutes for it to arrive.<br />";
return($success_message);
}
else if ($points < $price) {
$error_message .= "You have " . $points . " you need " . $price . " points to purchase a " . $name;
return($error_message);
}
else if (!$db_found) {
$error_message .= "Could not connect to the database, please contact support";
return($error_message);
}
}
}
if($Checked1 == true) {
product(400, $points, "Some string", $uname, $error_message, $success_message); //price and name
}
if($Checked2 == true) {
product(400, $points, "Some string", $uname, $error_message, $success_message);
}
if(strlen($error_message) > 0) {
died($error_message);
}
if(strlen($success_message) > 0) {
success($success_message);
}
echo "error didnt pass at all";
I could add the
header("Location: success_points_on.php?success=" . $success);
instead of a return, but I want the user to be able to purchase multiple items, (adding it instead of a return does work).
Your logic nesting is wrong. Stripping out the guts and leaving just the if statements, you have in your product() function:
function product($price,$points, $name, $uname, $error_message, $success_message) {
if ($db_found) { // connect to DB
if ($points >= $price) {
$success_message = "blah";
return($success_message);
}
else if ($points < $price) { // This if () part is redundant, btw
$error_message = "blah";
return($error_message);
}
else if (!$db_found) {
$error_message .= "blah"; // This should be = instead of .=
return($error_message);
}
}
}
What you want instead is:
function product($price,$points, $name, $uname, &$error_message, &$success_message) {
if ($db_found) {
if ($points >= $price) {
$success_message = "blah";
return($success_message); // this is redundant actually
} else {
$error_message = "blah";
return($error_message); // this is redundant actually
}
} else {
$error_message = "blah";
return($error_message); // this is redundant actually
}
}
I would strongly recommend the use of some tool such as an IDE which can keep your code formatted correctly, this will make these types of problems easier to see.
EDIT
I also just noticed that you are not passing $error_message and $success_message by reference which will cause further problems. Changes made above (in second example) but this code is still not what I would call best practice.
I agree with everything #leftclickben said above, but would like to add one more observation. I seems that you are using the value of $error_message and $success_message in the code that follows your call to product(), but TO LET THE FUNCTION CHANGE THEIR VALUE, YOU MUST PASS THEM BY REFERENCE, using the & symbol.
Change your function prototype to
function product($price,$points, $name, $uname, &$error_message, &$success_message) {
and changes in the value will be available after the function returns.