XML request MySQL by PHP - php

Actually i'm working in a flash web page using XML. I want to make a sing up page with XML that uses PHP to insert data into de MySQL database, but I'm stuck... and i my XML-PHP knowledge are not enough for this duty.
This is the XML file:
<?xml version="1.0" encoding="utf-8"?>
<data>
<title>Sing up</title>
<request field1="user" field2="email" field3="password" field4="other">reg.php</request>
<description><![CDATA[Please sing up!]]></description>
</data>
The reg PHP file:
<?php
function Reg()
{
if (isset($_POST['reg'])==true) {
require_once('db_conf.php');
$user = $_POST['username'];
$pass = sha1(strtoupper($user.':'.$_POST['password']));
$email = $_POST['email'];
$con = mysql_connect($dbhost, $dbuser, $dbpassword);
if (!$con)
{
die('Could not connect!');
} else {
mysql_select_db("$logondb", $con);
$sql="INSERT INTO accounts (username, sha_pass_hash, email) VALUES ('$user','$pass','$email')";
if (!mysql_query($sql,$con))
{
die('Error creating account.');
}
echo $succesmsg;
mysql_close($con);
}
} else {
?>
And PHP conf for database:
<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpassword = 'password';
// Accounts Database
$logondb = 'accounts';
$errormsg="Error creating account..";
$succesmsg="Account created!";
?>

I would like to suggest using PDO instead - it's a more general approach. And then you should use data-binding to reduce vulnerability against SQL Injections...
This should take you one step further:
<?php
function Reg()
{
if (isset($_POST['reg'])==true) {
require_once('./db_conf.php');
$user = $_POST['username'];
$pass = sha1(strtoupper($user.':'.$_POST['password']));
$email = $_POST['email'];
$dsn = "mysql:host=$dbhost;dbname=$logondb";
$pdo = new PDO($dsn,$dbuser,$dbpassword);
if (!$pdo)
{
die('Could not connect!');
} else {
$sql = "INSERT INTO accounts (username, sha_pass_hash,email) VALUES (:user,:pass,:email)";
$stmt = $pdo->prepare($sql);
$res = $stmt->execute(array("user"=>$user , "pass"=>$pass , "email" => $email));
if (!$res) {
echo "Error :((<pre>";
var_dump($stmt->errorInfo());
echo "</pre>";
} else
{
echo $succesmsg;
}
}
} else {
echo "reg was not set - terminating...!";
}
}
Reg(); // execute it!
?>

Related

Sql Statement from PHP isnt inserting into Database but doesnt give an error

Thanks to this site i could manage to solve my problems, but my statement isnt going through on my database, but when i copy it and paste it directly to my database, it inserts without any problem. Here my code:
<?php
$ip = "***"; //MySQL Server IP
$user = "***"; //MySQL user
$pw = "***"; //MySQL password
$db = "***"; //Database
$sql_filter = "";
$con = mysqli_connect($ip, $user, $pw, $db);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
function register()
{
$username = $_POST[username];
$vorname = $_POST[vorname];
$nachname = $_POST[nachname];
$geschlecht = $_POST[geschlecht];
$geburtsdate = $_POST[geburtsdatum];
$password = $_POST[password];
$email = $_POST[email];
if($email!="" and $password!="" and $username!="" and $password==$_POST["password_confirm"])
{
$sql_filter = "INSERT INTO `tblUser`(`UserID`, `UserName`, `Vorname`, `Nachname`, `EMail`, `Geschlecht`,`Password`) VALUES ('','$username','$vorname','$nachname','$email','$geschlecht','$password')";
$_SESSION['filter'] = $sql_filter;
$page_query = mysqli_query($con, $_SESSION['filter']);
$page_nums = mysqli_num_rows($page_query);
//header('Location: index.php');
echo $sql_filter;
echo $_SESSION['filter'];
}
else
{
header('Location: 404.html');
}
}
if(isset($_POST['submit']))
{
register();
}
mysqli_close($con);
?>
I think the problem is your $con is undefined in the function register(). So add this in the beginning of your function :
function register()
{
global $con;
... // the rest of your function
}

Contactus table schema

I have two HTML form in first form i am adding Id and product and second form is contact us form. I have created one table with column name is ID,Product,name,email,mobile.In first form i am adding id and product and rest of values are NULL,than form will redirect to contact us form there i am updating name,email,mobile..I am getting pop is updated successfully but when i checked in database there was no update....please help me
//insert code
<?php
try{
$product=$_POST['product'];
/*
$product2=$_POST['product2'];
$product3=$_POST['product3'];
*/
// form data
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
$insertQuery = "Insert into contactus(Id,Product) values('null','$product')";
$result = mysql_query($insertQuery);
mysql_close($conn);
header('Location: /newstore/contact.html');
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../index.html';</script>");
return false;
}
?>
//Update code
<?php
// Start the session
session_start();
?>
<?php
$_SESSION['user_name1']=$_POST['product'];
try{
// form data
$name=$_POST['name'];
$email=$_POST['email'];
$mobile=$_POST['mobile'];
$product=$_SESSION['user_name1'];
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
;if ((strlen($name) < 3) or (strlen($email) < 3) or(strlen($mobile) < 3))
{
echo ("<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>");
}else
{
//$insertQuery = "Insert into contactus(Id,Name,Email,Mobile,Product) values('null','$name','$email','$mobile','$product')";
//$UpdateQuery = "update contactus set Name='$name',Email='$email',Mobile='$mobile' where Product='$product' ";
$UpdateQuery = "update contactus set Name='".$name."',Email='".$email."',Mobile='".$mobile."' where Product='$product' ";
$result = mysql_query($UpdateQuery);
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../newstore/index.html';</script>";
}
else
{
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
}
}
mysql_close($conn);
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../newstore/index.html';</script>");
return false;
}
?>

Using PHP in HTML to send object values to mysql database

I am creating a website where it sends values from a JavaScript object into a MySQL database via PHP
Here is the code:
<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
</script>
</body>
</html>
Overall, my question is how to send the objects data to the MySQL using PHP?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
If I type the code in before it prints out:
connect_error) {die("Connection failed: " . $conn->connect_error);} echo "Connected successfully";?>
It sounds to me like you are trying to jump from not knowing how to work with PHP and MySQL to also adding JavaScript.
First let me give you an example of how to work with all of those things.
Here is the repo with all of these files: https://github.com/Goddard/simplelogin-example.
This is what connects you to the database:
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
define("__DB_NAME__", 'job');
define("__DB_DSN__", 'mysql:dbname=' . __DB_NAME__ . ';host=127.0.0.1');
define("__DB_USERNAME__", 'root');
define("__DB_PASSWORD__", '');
if(session_id() == '') {
session_start();
}
if(!isset($_SESSION['username']))
{
$_SESSION['username'] = NULL;
}
//database setup
try {
$db = new PDO ( __DB_DSN__, __DB_USERNAME__, __DB_PASSWORD__ );
$db->query ( "use " . __DB_NAME__);
}
catch ( PDOException $e ) {
echo 'Could not connect : ' . $e->getMessage ();
}
?>
This is what works with the database information:
<?php
include("db.php");
if(trim(htmlentities(addslashes(filter_input(INPUT_GET, 'type')), ENT_QUOTES)) === "loginUser")
{
try {
$username = trim(filter_input(INPUT_GET, 'username'));
$password = trim(filter_input(INPUT_GET, 'password'));
$fetch = $db->prepare("SELECT * FROM `users` WHERE user_name = :username");
$fetch->bindParam(':username', $username, PDO::PARAM_STR);
$fetch->execute();
$result = $fetch->fetch(PDO::FETCH_OBJ);
if($result)
{
if(password_verify($password, $result->password_hash))
{
$currentDateTime = date('Y-m-d H:i:s');
$update = $db->prepare("UPDATE `users` SET `last_login` = :lastlogin WHERE `client_id` = :clientid");
$update->bindParam(':lastlogin', $currentDateTime);
$update->bindParam(':clientid', $result->client_id);
$loginUpdate = $update->execute();
$resultArray['error'] = 0;
$resultArray['errorMessage'] = "None";
$resultArray['userName'] = $result->user_name;
$_SESSION['username'] = $result->user_name;
echo json_encode($resultArray);
}
else
{
$resultArray['error'] = 1;
$resultArray['errorMessage'] = "Incorrect Password";
echo json_encode($resultArray);
}
}
else
{
$resultArray['error'] = 1;
$resultArray['errorMessage'] = "Incorrect Username";
echo json_encode($resultArray);
}
} catch (PDOException $e) {
$resultArray['error'] = 1;
$resultArray['errorMessage'] = $e->getMessage();
echo json_encode($resultArray);
}
}

php mysql script not working

I got my script working for one column of data but I am trying to send it other data to a second column in mysql table. Here's my php code:
<?php
function db_connect()
{
$hostname = '127.0.0.1';
$db_user = 'root';
$db_password = '';
$db_name = 'hit';
mysql_connect ($hostname, $db_user, $db_password) or die (mysql_error());
echo "Success.. Connected to MySQL...<br />";
mysql_select_db($db_name) or die(mysql_error());
echo "Success.. Connected to Database...<br /> ";
}
function insertData($DATA)
{
function insterData($DATA2)
{
db_connect();
$requete = "INSERT INTO data SET col_Data='".$DATA."'";
if(!mysql_query($requete))
echo mysql_error();
else
echo 'data accepted.';
$requete2 = "INSERT INTO data SET col_Data2='".$DATA2."'";
if(!mysql_query($requete2))
echo mysql_error();
else
echo 'data accepted.';
}
if(isset($_GET['DATA']))
if(isset($_GET['DATA2']))
}
insertData($_GET['DATA']);
insertData($_GET['DATA2']);
}
else
{
echo 'Nop';
}
?>
This is how I send the post data
http://localhost/hit.php?DATA=iamwicked&DATA2=iamcool
This then suppose to send DATA=iamwicked goes into database hit table data column col_data
This then suppose to send DATA2=iamcool goes into database hit table data column col_data2
But I get this error,
but there are errors can someone help me debug.
Here is a working script:
<?php
function db_connect()
{
$hostname = '127.0.0.1';
$db_user = 'root';
$db_password = '';
$db_name = 'hit';
mysql_connect ($hostname, $db_user, $db_password) or die (mysql_error());
echo "Success.. Connected to MySQL...<br />";
mysql_select_db($db_name) or die(mysql_error());
echo "Success.. Connected to Database...<br /> ";
}
function insertData($DATA)
{
db_connect();
$requete = "INSERT INTO data SET col_Data='".$DATA."'";
if(!mysql_query($requete))
echo mysql_error();
else
echo 'data accepted.';
}
if(isset($_GET['DATA']))
{
insertData($_GET['DATA']);
}
else
{
echo 'Nop';
}
?>
this is a working script when I use this url to post data
localhost/hit.php?DATA=iamwicked
When I use this it save iamwicked in database hit table data column col_data
so how do I fix my script to send more data to col_data2 and so forth
Return $conn connection resource #id from function
<?php
function db_connect()
{
$hostname = '127.0.0.1';
$db_user = 'root';
$db_password = '';
$db_name = 'hit';
$conn = mysql_connect ($hostname, $db_user, $db_password) or
die (mysql_error());
echo "Success.. Connected to MySQL...<br />";
mysql_select_db($db_name) or die(mysql_error());
echo "Success.. Connected to Database...<br /> ";
return $conn;
}
$conn = db_connect();
To insert single field
function insertData($DATA)
{
$requete = "INSERT INTO data SET col_Data='".$DATA."'";
mysql_query($requete) or die(mysql_error());
}
if(isset($_GET['DATA'])) {
insertData($_GET['DATA']);
}
if(isset($_GET['DATA2'])) {
insertData($_GET['DATA2']);
}
UPDATE
To insert multiple fields
function insertData($DATA, $DATA2)
{
$requete = "INSERT INTO data SET col_Data='".$DATA."', col_Data2='".$DATA2."'";
mysql_query($requete) or die(mysql_error());
}
if(isset($_GET['DATA']) && isset($_GET['DATA2'])) {
insertData($_GET['DATA'], $_GET['DATA2']);
}
?>
I think you have an wrong spelling here:
function insertData($DATA2) instead of function insterData($DATA2);
There are indeed two problems here.
function insertData($DATA)
{
function insterData($DATA2)
{
What are you trying to achieve here? Declaring a function inside another function is totally useless (and generates errors since it's not allowed). If you want to call a function inside another one you must declare them separately and then call them, f.e.
function insertData($DATA)
{
insterData($somevariable);
//Rest of the operations
}
This should be clear enough. There is another error though.
if(isset($_GET['DATA']))
if(isset($_GET['DATA2']))
}
insertData($_GET['DATA']);
insertData($_GET['DATA2']);
}
else
{
echo 'Nop';
}
I suppose there is a typo here, and you meant
if(isset($_GET['DATA2']))
{

Why won't the data be stored in my database?

Sorry I am new to php so please be patient with me. I am creating a user interface and when I register it says I have registered but it doesn't store the data into the database. can someone please help me!
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
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;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
$uLength = strlen($uname);
$pLength = strlen($pword);
if ($uLength >= 10 && $uLength <= 20) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Username must be between 10 and 20 characters" . "<BR>";
}
if ($pLength >= 8 && $pLength <= 16) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Password must be between 8 and 16 characters" . "<BR>";
}
if ($errorMessage == "") {
$user_name = "root";
$pass_word = "";
$database = "user authentication";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "Username already taken";
}
else {
$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
}
else {
$errorMessage = "Database Not Found";
}
}
}
?>
<html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION ="signup.php">
Username: <INPUT TYPE = 'TEXT' Name ='username' value="<?PHP print $uname;?>" maxlength="20">
Password: <INPUT TYPE = 'TEXT' Name ='password' value="<?PHP print $pword;?>" maxlength="16">
<P>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Register">
</FORM>
<P>
<?PHP print $errorMessage;?>
</body>
</html>
You might also want to rather make use of PDO then you don't have to to do the cleanup of the user input as PDO will take care of that for you. You might want to creat a file that hold all your connection details like this:
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'user authentication');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DSN', 'mysql:host='. DB_HOST . ';dbname=' . DB_NAME);
?>
You then might want to create a class to do the connection to your database like:
<?php
class database{
public function databaseConnect(){
/*Creates a new instance of the PDO called $db.
* NOTE: the use of DSN, DB_USER and so on. These variable live in the dbsettings file.
*/
$db = new PDO(DSN,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
}
?>
Then you might want to create a class to register your user like:
<?php
//Include the database class file to allow access to properties and methods within that class.
require_once 'class.database.php';
//echo 'I am database class file now included in the users class file. <br />';
//This method will be user to check if the user enter the correct username password pair.
class users{
public function checkValidUser($username){
$userExists = false;
try {
$db = database::databaseConnect();
$stmt = $db->prepare('SELECT uname FROM table WHERE uname=:username');
$stmt->bindParam(':uname', $username, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() == 1){
$userExists = true;
}
$db = null;
} catch (PDOException $e) {
$userExists = false;
}
return $userExists;
}
public function addUser($firstname, $lastname, $username,$password){
$success = true;
//Connect to the database
try {
$db = database::databaseConnect();
//$db->databaseConnect();
$stmt = $db->prepare('INSERT INTO table (FirstName, LastName, Username, Password) VALUES (:firstname, :lastname, :username, :password)');
$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
$stmt->bindParam(':lastname', $lastname, PDO::PARAM_STR);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$success = $stmt->execute();
if ($success){
$success = true;
}
$db = null;
} catch (PDOException $e) {
//echo 'There was an error adding a new user. Please go back and try again. If this problem persits please contact the administrator.';
$success = false;
}
return $success;
}
?>
Hope that this helps.
enter link description here$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
You're not inserting the values into proper fields, it appears. You're inserting the $uname into L1 and md5($pword) into L2 but in the select query above, you have a different field name for username and I presume the same for password.
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
Most likely, your insert query should be something like:
$SQL = "INSERT INTO login (USERNAME, PASSWORD) VALUES ('{$uname}', MD5('{$pword}'))";
I added single quotes around the username and password since presumably they are strings. Also, I added curly braces around the variables to segregate what is SQL from what is PHP.
One last thing, I would check into doing this with PDO as Willem suggested

Categories