Copying data from a MySQL table to another MySQL table not showing - php

I'm trying to make a registration form that validates the account by sending a validation code to the email. Once the user receive the code in his email he must click the link to validate his account(I simulated this using the localhost). BTW, I have 2 database for the registered members and for the temporary members(these are the members that are waiting for validation).
When the validation code is processed and matched, the data from the temporary table will be copied to the registered members table, after the copying is done the user data from temporary table will deleted.
when I checked my updated database(registered members table) the ID column had incremented but the username, password and email field has no data. what is the problem here?
here is the website I'm following for the tutorial but I did some little tweaks
http://phpeasystep.com/phptu/24.html
localhost/validated_email.php?passkey=639900974e5fc25626af1a6ce5da8b01
<html>
<body>
<?php
ob_start();
//define a function for temporary database (temporary_members)
function temporary_members_db(){
$host="localhost";
$db_username="root";
$db_password="";
$db="forum_members";
$db_table="temporary_members";
//=======================connect to database
mysql_connect("$host","$db_username","$db_password") or die("Could not connect to the database!");
mysql_select_db("$db") or die("database not found!");
}
function members_db() {
$host="localhost";
$db_username="root";
$db_password="";
$db="forum_members";
$db_table="members";
//=======================connect to database
mysql_connect("$host","$db_username","$db_password") or die("Could not connect to the database!");
mysql_select_db("$db") or die("database not found!");
}
//connect to the temporary_member table
temporary_members_db();
$code = $_GET['passkey'];
//execute mysql query to check the validation code
$check_code = "SELECT `validation_code` FROM `temporary_members`";
$execute_code = mysql_query($check_code);
$result_code = mysql_num_rows($execute_code);
if ($result_code==1) {
$rows=mysql_fetch_array($execute_code);
$username = $rows['username'];
$password = $rows['password'];
$email = $rows['email'];
$table_members = "members";
members_db();
$copy_values = "INSERT INTO $table_members(username, password, email) VALUES ('$username', '$password', '$email')";
$execute_copy = mysql_query($copy_values);
}
else {
echo "Wrong validation code";
}
if ($execute_copy) {
echo "Your account has been activated!";
//delete data from the temporary_members
$table_temporary_members = "temporary_members";
$delete_data = "DELETE FROM $table_temporary_members WHERE validation_code = '$code'";
$execute_delete = mysql_query($delete_data);
}
ob_end_flush();
?>
</body>
</html>

Related

PHP MySQL. Add table contents does not work

If I want to add content to the table using "INSERT INTO", I don't get an error message and the table is not filled. I'm new with PHP. explanations would be nice. The database runs on XAMPP.
I don't know what to try. I've already used another table, but it doesn't work. The user should have full access to the table. The names also match.
<?php
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if($passwort == $passwort2) {
echo "Password is correct.";
$db = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
} else if(!($passwort == $passwot2)) {
echo "Password is not correct";
} ?>
The variable $db actually contains information about the connection. You cannot insert a query into your database the way you are trying to
You can use $db (in your case) in order to check whether the connection has been correctly established or not and then if everything works correctly you can user mysqli_query() to inject the query into your database.
You can do it like so:
<?php
if(isset($_POST['submit'])){ //You have to check if your submit button is pressed
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if(!$db){
die('Connection could not be established! Check provided information');
}
if($passwort == $passwort2) {
echo "Password is correct.Inserting query now";
$query = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
$result = mysqli_query($db, $query); //keep $result for debugging purposes.
} else {
die("Password is not correct");
} //no need for else if as there are only 2 conditions.
if(!$result){ //check if query was successful.
die('Query Error');
}
echo "Query Updated successfully";
}
?>
This code is really simplistic and for testing purposes only.
I just wanted to show you the way you can send queries to your database. You better use other encryption techniques i.e. crypt() and of course functions like mysqli_real_escape_string() when retrieving data from users, in order to avoid potential injection attacks.
Check this post for more info about preventing injections.
Hope that helps.

Query running in PHPmyadmin but not through PHP

I am trying to run a query from PHP which is not running but I can run the query from within phpMyAdmin
here is the code
<?php
ob_start();
//Delete Item question to admin and delete product
include"../storescripts/connect_to_mysql.php";
$conn = mysql_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete the item with ID '.$_GET['deleteid'].' ?Yes|No';
exit();
}
if(isset($_GET['yesdelete'])){
// Delete the actual product and delete picture also
//delete from database
$id_to_delete = $_GET['yesdelete'];
$manager=preg_replace('#[^A-Za-z0-9]#i','',$_GET['yesdelete']);
//$sql=mysql_query("SELECT id FROM admin WHERE username = '$manager' AND password='$password' LIMIT 1 ");
$sql = mysql_query( $conn ,"DELETE FROM products WHERE id=`$id_to_delete` LIMIT 1 ") or (mysql_error());
//echo 'The data at number ' . $id_to_delete . ' Deleted Sucessfully';
//mysqli_query("DELETE * FROM products WHERE id=`$id_to_delete`LIMIT1");// or (mysql_error());
//Unlink file from server
$pictodelete=("../inventory_images/$id_to_delete");
//echo $pictodelete;
if(file_exists($pictodelete)){
unlink($pictodelete);
}
// header("location:inventory_list.php");
//exit();
}
?>
I am new to PHP so your help is sought, i am able to connect to to database at another instance the code of which is following
<?php
//checking the user
ob_start();
session_start();
if (!isset($_SESSION["manager"])){
header ("location:admin_login.php");
exit();
}
//be sure to check if this manager SESSION value is in the database
$managerID=preg_replace('#[^0-9]#i','',$_SESSION["id"]);
$manager=preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["manager"]);
$password=preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);
//runMYSQL query to assertain that this is manager
//Connect to mysql database
include"../storescripts/connect_to_mysql.php";
$sql=mysql_query("SELECT*FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password'LIMIT 1");
// make sure person exists in database
$existCount=mysql_num_rows($sql);
if ($existCount== 0)
{
echo "your data do not match our records";
exit();
}
?>
The code in connect_to_my_sql.php is as follows
<?php
/*
1: "die()" will exit the script and show an error statement if something goes wrong with the "connect" or "select" functions.
2: A "mysql_connect()" error usually means your username/password are wrong
3: A "mysql_select_db()" error usually means that the database does not exist
*/
// Place db host name Sometimes "localhost" but
// sometimes looks like this:>> ???mysql??.someserver.net
$db_host = "localhost";
//Place the username for the MySQL database here
$db_username = "storeuser";
//Place the password for the MySQL database here
$db_pass = "rajjar";
//Place the name for the MySQL database here
$db_name="mystore";
// Run the actual connection here
$conn = mysql_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");
//mysql_select_db("$db_name") or die ("no database");
?>

Unable to add user data into MySQL table by phonegap

I'm developing a phonegap app and currently trying to implement a registration form for users to sign up, then add their username, email and password into MySQL phpadmin database. However, after many trials, user data didn't add into sql database and I'm not so sure where the problem is.
I have one connect.php file: `
$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('test');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
?>
`
and another signup.php file: `
require('connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST['signup-username']) && isset($_POST['signup-email']) && isset($_POST['signup-password'])){
$signup-username = $_POST['signup-username'];
$signup-email = $_POST['signup-email'];
$signup-password = $_POST['signup-password'];
$query = "INSERT INTO `signup` (Username, E-mail, Password) VALUES ('$signup-username', '$signup-email', '$signup-password')";
$result = mysql_query($query);
if($result){
$msg = "User Created Successfully.";
}
}
?>
`
I would try using the Mysql Improved extension, http://php.net/manual/en/book.mysqli.php

Pass value from one php file to another php file

I create php file for my login.....
<?php
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$myusername=mysql_real_escape_string($_POST['uname']);
$mypassword=mysql_real_escape_string($_POST['passwd']);
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT uid FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if($row = mysql_fetch_assoc($result))
//echo mysql_result($result,0); // for correct login response
{
echo "User Found";
}
else {
echo "No Such User Found";
}
?>
It is just like this way...So here I select uid. I want get this uid & connect it to another php file. Really I want to get the details of the registered user by mapping so many tables. So I wrote the php file for that also. In the query inside that php file I want to equal the uid I get from above php file to the user_locator_tbl(the table in my database) uid. I did that. But I didn't think its correct. So pls help me.......
I gave here my other php file also....also I'm not fluent php...It is new to me...
<?php
require_once("dataget.php");
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
// Table name
$conn = mysqli_connect($host,$user,$pswd,$db);
//mysql_select_db($db, $conn);
//run the query to search for the username and password the match
//$query = "SELECT * FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$query = "select user_master.uid,device_locator_tbl.imei,device_locator_tbl.speed,device_locator_tbl.datetime,device_locator_tbl.number,device_master.icon
from device_locator_tbl,device_master,device_registration,user_master where user_master.uid=device_registration.uid
AND device_registration.imei=device_master.imei AND device_registration.imei=device_locator_tbl.imei AND user_master.uid='$query'";
//echo ($result);
$resultarray = mysqli_query($conn,$query) or die("Unable to verify user because : " );
//if($row = mysql_fetch_assoc($result))
if($row = mysqli_fetch_assoc($resultarray))
//echo mysql_result($result,0); // for correct login response
{
$rows[] = $row;
}
// close the database connection
mysqli_close($conn);
// echo the application data in json format
echo json_encode($rows);
?>
First off, you should use prepared statements, the mysql_ functions are deprecated in PHP and create a real issue for SQL injection, particularly in a login.
But using your example, refer to: PHP Login & MySql Query
The questioned code & answer there is perfectly pertinent to what you have thus far, and a simple, vastly more secure way to accomplish everything you need:
The original posters script you see is meant to store the users info into a $_SESSION[] array, from the database query like you have. Once the login attempt is validated the header(location:) call that you see in the original questions code will redirect the user to the location required.
Once the user is redirected, all the information from your user table query will be stored in the $_SESSION array and from then on accessible like $_SESSION[loggedinuser][userid], $_SESSION[loggedinuser][email] etc.
Remember to configure your PHP install appropriately for destroying sessions via a timeout, and also consider a logout function to destroy the user session.
So you should edit your first page like this ONLY IF you are NOT/CANNOT switching over to PDO - remember if you use sessions you should start session on page top:
<?php
session_start();
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$myusername=mysql_real_escape_string($_POST['uname']);
$mypassword=mysql_real_escape_string($_POST['passwd']);
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT uid FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if($row = mysql_fetch_assoc($result))
//echo mysql_result($result,0); // for correct login response
{
$_SESSION['uid'] = $row['uid'];
header("Location: nextpage.php");
//echo "User Found";
}
else {
echo "No Such User Found";
}
?>
And You can catch this value from next page like this:
<?php
session_start();
// this section validate your inner files no one can enter this file without login
if(empty($_SESSION['uid'])){
header("Location: index.php");
}
// now you can do whatever you like
echo $_SESSION['uid'];
require_once("dataget.php");
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
// Table name
$conn = mysqli_connect($host,$user,$pswd,$db);
//mysql_select_db($db, $conn);
//run the query to search for the username and password the match
//$query = "SELECT * FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$query = "select user_master.uid,device_locator_tbl.imei,device_locator_tbl.speed,device_locator_tbl.datetime,device_locator_tbl.number,device_master.icon
from device_locator_tbl,device_master,device_registration,user_master where user_master.uid=device_registration.uid
AND device_registration.imei=device_master.imei AND device_registration.imei=device_locator_tbl.imei AND user_master.uid='$query'";
//echo ($result);
$resultarray = mysqli_query($conn,$query) or die("Unable to verify user because : " );
//if($row = mysql_fetch_assoc($result))
if($row = mysqli_fetch_assoc($resultarray))
//echo mysql_result($result,0); // for correct login response
{
$rows[] = $row;
}
// close the database connection
mysqli_close($conn);
// echo the application data in json format
echo json_encode($rows);
?>

PHP how to check for email already in MySQL database?

Hi I'm calling out for help from all the PHP Gods on Stackoverflow :)
I've created an email signup form (just 1 field for email), that is able to validate with Ajax and post a new email to the database from a basic PHP script I found.
However the next step I have to do is check if an email is already in the database before adding it. There are several questions exactly like this on Stack and I've tried all the answers however to no avail :( I'm not a PHP guy and haven't been able to hack it right yet.
Below is my current insert.php file which does work and does add a new email field into the database. However the code below that is the latest I've tried to use to check for an already existing email, but I get a send data error.
Working PHP file to add email
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydatabase", $con);
$sql="INSERT INTO newsletter (email)
VALUES
('$_POST[mail]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "Thanks for subscribing!"; //Text on page
//header("Location: /thankyoupage.php"); //Redirect page
mysql_close($con)
?>
UPDATED CODE using PDO
Code below works to add emails, however still allows duplicates...
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = 'root';
/*** email ***/
$email = '$_POST[mail]';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mydatabase", $username, $password);
//$query = SELECT count(*) AS `total` FROM `data` WHERE `email` = '{$request}'
$query = SELECT COUNT(*) as 'count' FROM `data` WHERE email = '$_POST[mail]';
$row = mysql_fetch_assoc(mysql_query($query));
if($row['total']) {
echo 'Sorry email already exists';
}
else {
/*** echo a message saying we have connected & added email ***/
echo 'Thanks for subscribing!';
/*** INSERT data ***/
$count = $dbh->exec("INSERT INTO newsletter(email) VALUES ('$_POST[mail]')");
}
/*** echo a message saying we have connected & added email ***/
//echo 'Thanks for subscribing!';
/*** INSERT data ***/
//$count = $dbh->exec("INSERT INTO newsletter(email) VALUES ('$_POST[mail]')");
/*** echo the number of affected rows ***/
/*echo $count;*/
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Thanks in advance for anyone with the time to take a look at this :)
Extra Notes:
My database table is called newsletter and there are 2 fields (id - numbers only) & (email)
if email is an unique key, that would be simple
<?php
mysql_connect("localhost","root","root");
mysql_select_db("howdini");
$email = mysql_real_escape_string($_POST['mail']);
$sql="INSERT IGNORE INTO newsletter (email) VALUES ('$email')";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if (mysql_affected_rows()) {
header("Location: /thankyoupage.php"); //Redirect page
} else {
//already exists
}

Categories