I don't know what's wrong but the moment i've logged in, i wanted it to display hello + username that i log in with. But currently it only displays Helloundefined
This is my flash code:
var myurl2:String = "http://localhost:8888/storyboards/check_auth.php";
var scriptLoader2:URLLoader = new URLLoader();
var scriptRequest2:URLRequest = new URLRequest();
scriptRequest2.url = myurl2+"?ck=" + new Date().getTime();
scriptLoader2.addEventListener(Event.COMPLETE, handleLoadSuccess2);
scriptLoader2.addEventListener(IOErrorEvent.IO_ERROR, handleError2);
// turn off right click so that user cannot control the movie
stage.showDefaultContextMenu = false;
scriptRequest2.method = URLRequestMethod.POST;
scriptLoader2.load(scriptRequest2);
function handleLoadSuccess2(evt:Event):void
{
var variables2:URLVariables = new URLVariables( evt.target.data );
for (var prop in variables2) {
trace(prop+" is: "+variables2[prop]);
}
if (variables2.authenticated == "y") {
// if login details OK, load protected page
nextFrame();
display_txt.text ="Hello" + variables2.username;
} else {
// if login details OK, load protected page
var url:String = "http://localhost:8888/storyboards/login.html";
var request2:URLRequest = new URLRequest(url);
try {
navigateToURL(request2, '_self'); // second argument is target
} catch (e:Error) {
trace("Error occurred!");
}
}
}
function handleError2(evt:IOErrorEvent):void
{
}
stop();
//------------------and here's my php code for process_login.php----------------------//
<?php
$host = 'localhost';
$user = 'root';
$password = 'root';
// check correct variables have been received through the POST array
if (isset($_POST['username']) && isset($_POST['pwd'])){
session_start();
// base url
$baseURL = 'http://localhost:8888/storyboards/';
// include info for db connection
//require_once("connection.php");
// escape quotes
if (!get_magic_quotes_gpc()) {
foreach($_POST as $key => $value) {
$temp = addslashes($value);
$_POST[$key] = $temp;
}
}
// connect to mysql
$connection = mysql_connect($host, $user, $password) ;
if (!$connection) {
echo '&error=' . mysql_error() . '&';
die('Could not connect ' . mysql_error());
}
//echo 'Connected successfully.';
// connect to db
$database = 'registerform';
$db = mysql_select_db($database, $connection);
if (!$db) {
echo '&error=' . mysql_error() . '&';
die ('Not connected : ' . mysql_error());
}
//echo 'Selected successfully.';
// query
$query = 'SELECT user_name, pwd FROM users WHERE user_name = "' . $_POST['username'] . '" AND pwd = "' . sha1($_POST['pwd']) . '"';
$result = mysql_query($query, $connection);
if (!$result) {
echo '&error=' . mysql_error() . '&';
die ('Invalid query: ' . mysql_error());
}
// count the number of records
$numrows = mysql_num_rows($result);
if ($numrows > 0) {
$_SESSION['authenticated'] = $_POST['username'];
echo 'authenticated=y' . '&page=' .'pass.php&user_name='.$_SESSION['authenticated'];
} else {
echo 'authenticated=n&error=' . urlencode('Sorry, access denied.');
}
}
?>
//-----------and my php code for check_auth.php----//
<?php
// access to the current session
session_start();
$_SESSION['username'] = $_POST['username'];
// if session variable authenticated is not set
if (!isset($_SESSION['authenticated'])) {
echo 'authenticated=n';
} else {
echo 'authenticated=y';
}
?>
Is there anywhere in the above codes that I went wrong? Can someone out there pls help me :(
Related
I am trying to connect to a db but I keep getting an error that pops up every chance I get to change the db or connection string . I am currently using php mysqli and wamp will not show any error with the connection itself .
calc.php:
class Login {
var $con;
function __construct($con){
$this->con = $con;
}
function try_connecting(){
$connecting = true;
if($connecting){
if(!$this->con){
die ("Could not connect") . $this->con->connect_errno;
} else {
echo "connected";
}
} else {
return $connecting;
}
}
function try_login(){
if(try_connecting()){
$q = "SELECT username, password FROM persons WHERE username = " . $_POST["username"] . " AND password = " . $_POST['pwd'];
$rows = $this->con->num_rows;
if($rows == 1){
echo "true";
} else {
echo "not user";
}
}
}
}
Here is the test.php:
<?php
include("calc.php");
$u = $_POST['username'];
$p = $_POST['pwd'];
$con = mysqli_connect("localhost","root","","rdb");
$form = new Login($con);
$form->try_connecting();
$form->try_login();
?>
connection string error Unknown database
You forgot to run this query
$q = "SELECT username, password FROM persons WHERE username = " . $_POST["username"] . " AND password = " . $_POST['pwd'];
$rows = $this->con->num_rows;
Try to add
$this->con->query($q)
between the lines above
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);
}
}
I just want to test db connection from my browser. But i get empty page. I am not getting Error message.
<?php
$con = mysqli_connect('http://ec2-54-67-69-153.us-west-1.compute.amazonaws.com/', 'root', 'root') or die(mysqli_error($con));
if ($con) {
echo "success";
} else {
echo "fail";
}
mysqli_close($con);
?>
**Here is a handy function that connects you to a Database, using *Object Oriented* style:**
function MySQLi_quickConnect()
{
$host = 'somewebsite.db.120327161.hostedresource.com'; //or 'http://localhost'
$username = '<YOUR USERNAME>';
$password = '<YOUR PASSWORD>';
$database = '<YOUR DATABASES NAME>';
$db = new MySQLi($host,$username,$password,$database);
$error_message = $db->connect_error;
if($error_message != NULL){die("Error:" . $error_message . "<br>" . "Occured in function
MySQLi_quickConnect");}
return $db;
}
**A simple example on how you would query the Database:**
$db = MySQLi_quickConnect(); //this is your new Database object
$sql = "<YOUR SQL STATEMENT>";
$stmt = $db->query($sql);
if(!$stmt){die('MyError : ('. $db->errno .') '. $db->error);} //kill script, show errors
I have a php function of selection from mySql database:
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
$db=mysql_select_db($NAME_DB);
$qry = "SELECT tax_id FROM master where name =".$name." and latin =".$latin;
echo $qry;
$result = mysql_query($qry);
while ($Res_user = mysql_fetch_assoc($result) ) {
return $Res_user['tax_id'];
}
}
an error is shown Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/admin/public_html/hitlist/include/fg_membersite.php on line 446 and the line is while ($Res_user = mysql_fetch_assoc($result)
So what is the problem ? How can i fix it?
Try this
function Master_file($name, $latin ){
$dsn = 'mysql:host=localhost;dbname=nom';
$username = 'utilisaeur';
$password = 'K3Pud1';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
$result = $db->prepare("SELECT tax_id FROM master where name =:name");
$result->bindValue(':name', $name);
$result->execute();
foreach($result->fetchAll(PDO::FETCH_ASSOC) as $row){
echo $Res_user['tax_id'] . '<br />';
}
}
EDIT
The function above has just been updated to use PDO, display any errors, and output the tax_id value to the browser
You may try this, since your returning here return $Res_user['tax_id']; so I think you need a single row instead
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
if (!$connect) {
die("Could not connect: " . mysql_error());
}
$db=mysql_select_db($NAME_DB, $connect);
if (!$db) {
die ("Can't use " . $NAME_DB . " : " . mysql_error());
}
$qry = "SELECT tax_id FROM master where name ='" . $name . "' and latin = '" . $latin . "'";
$result = mysql_query($qry);
if( $result ){
$row = mysql_fetch_assoc($result);
return $row['tax_id'];
}
}
I'm have a problem with an invite system. The if statement seems to break. It shows the message "Fail" but the UPDATE statement still executes. Why do both the THEN and the ELSE excute?
$dbConn = new dbConn();
// Check if POST user_username and user_hash are matching and valid; both are hidden for fields
$sql = "SELECT user_username "
. "FROM table_users "
. "WHERE user_id=".mysql_real_escape_string($_POST["user_id"])." "
. "AND user_hash='".mysql_real_escape_string($_POST["user_hash"])."' "
. "AND user_enabled=0;";
$objUser = $dbConn->query($sql);
// If result contains 1 or more rows
if( mysql_num_rows($objUser) != NULL ){
$objUser = mysql_fetch_assoc($objUser);
$ssnUser->login( $objUser["user_username"] );
$sql = "UPDATE table_users SET "
. "user_enabled=1, "
. "user_first_name='".mysql_real_escape_string($_POST["user_first_name"])."', "
. "user_last_name='".mysql_real_escape_string($_POST["user_last_name"])."', "
. "user_password='".mysql_real_escape_string( md5($_POST["user_password"]) )."' "
. "WHERE user_id=".mysql_real_escape_string($_POST["user_id"]).";";
$dbConn->query($sql);
echo "Success";
header( "Refresh: 5; url=/account/?action=domains" );
} else {
echo "Fail";
}
This dbConn Class is as follows:
class dbConn{
var $username = "xxxx_admin";
var $password = "xxxxxxxx";
var $server = "localhost";
var $database = "xxxx";
var $objConn;
function __construct(){
$conn = mysql_connect( $this->server, $this->username, $this->password, true );
if( !$conn ){
die("Could not connect: ".mysql_error() );
} else {
$this->objConn = $conn;
}
unset($conn);
}
function __destruct(){
mysql_close( $this->objConn );
unset( $this );
}
function query( $query, $db = false ){
mysql_select_db( $db != false ? $db : $this->database, $this->objConn );
$result = mysql_query( $query );
unset($query,$db);
return $result;
}
}
I don't see anything really weird in your code. Could there be a "Fail" call in your login() method? Either way, I would change the line:
if( mysql_num_rows($objUser) != NULL ){
to:
$rowCount = mysql_num_rows($objUser);
if($rowCount and $rowCount > 0){
And, put an exit(); call after your header() line.