Blank page after attempt to insert - mysql

Whenever I try to insert data into my database 'users' I always get a blank page. It doesn't give me any errors, it doesn't include 'mainmenu.php', or return any feedback what so ever. Can someone help me out? Here is the code:
<?php
include("mainmenu.php");
$con = mysql_connect("localhost", "root", "*********");
if (!$con) {
die('Connection failure.' . mysql_error());
}
//Variable def
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$usrname = $_POST['usrname'];
$password = $_POST['password'];
mysql_select_db("users",$con) or die(mysql_error());
mysql_query("INSERT INTO data (usrname, fname, lname, password, email) VALUES ($usrname, $fname, $lname, $password, $email)") or die(mysql_error());
mysql_close($con)
echo("Thank you for registering!")
?>
It looks right to me.

don't you getting any syntax error?
first
mysql_close($con)
echo("Thank you for registering!")
change to
mysql_close($con);
echo("Thank you for registering!");
second, please quote your $_POST and escape it properly
read this - Escaping single quote in PHP when inserting into MySQL)

No errors? Add this at the top of the script:
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );

First of all: Strings need delimiting:
mysql_query("INSERT INTO data (usrname, fname, lname, password, email) VALUES ('$usrname', '$fname', '$lname', '$password', '$email')";
Second: never ever pass un-checked user data into a database query. Use mysql_real_escape_string() on each value first.

mysql_query("INSERT INTO data (usrname, fname, lname, password, email) VALUES ($usrname, $fname, $lname, $password, $email)") or die(mysql_error());
Use this instead
$insert_sql = sprintf("INSERT INTO users (usrname, fname, lname, password, email) " .
"VALUES ('%s' ,'%s', '%s', '%s', %d); ",
mysqli_real_escape_string($conn, $usrname),
mysqli_real_escape_string($conn, $fname),
mysqli_real_escape_string($conn, $lname),
mysqli_real_escape_string($conn, md5($password)),
mysqli_real_escape_string($conn, $email),
mysqli_insert_id($conn));
Then Query The Above String
mysqli_query($conn, $insert_sql);
Then a Conditionals
if($insert_sql){
$usrname = $_SESSION['user_id'];
//url.ext e.g could be "home.php" or "you.html"
//header is used for redirecting a page
header("Location: url.ext");
}else{
$msg = "error inserting";
header("Location: " . $_SERVER['HTTP_REFERER'] . "?Message= ". $msg );
}

Related

how to add name number email id to my mysql database

i have created a website with shared hosting from a company and i have created themes and fronted end development is completed. now the problem is
If some one visited my site and entered their details in temple having name, mail,number.
So how i can see those name and email and number in my mysql database.
I have installed mysql database.
Assuming visitors already have filled a HTML <form> element and data are inserted into the database, you will need to execute a SELECT statement to get the visitors details.
SELECT name, mail, number FROM [tableName]
Here's a PHP example :
<?php
$host = "127.0.0.1";
$user = "myuser";
$pass = "mypass";
$bdd = "mydatabase";
try {
$objBdd = new PDO("mysql:host=$host; dbname=$bdd; charset=utf8", $user, $pass) ;
$objBdd->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION );
} catch(Exeception $prmE) {
die('Error : ' . $prmE->getMessage()) ;
}
$getMyVisitors = $objBdd->query("SELECT name, mail, number FROM myTable");
while ($visitorData = $getMyVisitors->fetch()) {
echo "----\r\n";
echo "Name : " . $visitorData['name'] . "\r\n";
echo "Mail : " . $visitorData['mail'] . "\r\n";
echo "Number : " . $visitorData['number'] . "\r\n";
echo "----\r\n";
}
$getMyVisitors->closeCursor();
$objBdd = NULL;
Every statements using dynamic user data (example: username, password, comments ...) should be prepared.
If you want to use a WHERE condition, use prepared statements like
$getMyVisitors = $objBdd->prepare("SELECT name, mail FROM myTable WHERE number = ?");
$getMyVisitors->execute(array("+33000000000"));
Now, if the visitors informations are not saved in the database, you will need to create a HTML form element.
Your HTML form element should looks like :
<form action="myScript.php" method="POST">
<input type="submit" value="Send my informations">
</form>
Where myScript.php is a PHP script that will save the visitor's informations into the database. Use my example above to make that script, you will need to use an INSERT statement.
You will need to add input elements in the form as much as you need, in your case, three (name, mail, number).
Note that you will need to set the name attribute to each of your inputs to be able to get the inputs value in your PHP.
Example : <input type="email" name="visitorMail"> goes with $myVisitorMail = $_POST['visitorMail'];.
You Could directly use php to do this task! The sample code would get you going around!
You could view there details by firing query like
SELECT Name,Phone,Email FROM Customers
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Connecting mySQL db through PHP

Let me begin by saying I am extremely new at this. I am trying to develop a mobile app and a website with no real experience. There is likely something that I have missed or I am doing wrong but I cannot seem to pin point where the issue is. Prior to creating my own, I followed a video guide (with the demo files downloaded to my computer) but cannot seem to connect to my database. I have also copied the demo files and placed them into my code and it is still getting me caught on one section. I am using the program MAMP for the connection and Brackets for the code. Below are my session files:
Database connection-
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "Login System";
$con = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
My sign up document-
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
//Error handlers
//Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($uid) || empty($pwd)) {
echo <h2>Please fill in all fields;
exit ();
} else {
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
header("Location: ../signup.php?signup=invalid");
exit();
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=email");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the user into the database
$sql = "INSERT INTO users (first, last, email, uid, pwd) VALUES ('$first', '$last', '$email', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
} else {
header("Location: ../signup.php");
exit();
}
?>
My Login Sheet
<?php
include_once 'header.php';
?>
<section class="main-container">
<div class="main-wrapper">
<h2>Signup</h2>
<form class="signup-form" action="includes/signup.inc.php" method="POST">
<input type="text" name="first" placeholder="Firstname">
<input type="text" name="last" placeholder="Lastname">
<input type="text" name="email" placeholder="E-mail">
<input type="text" name="uid" placeholder="Username">
<input type="password" name="pwd" placeholder="Password">
<Button type="submit" name="submit">Sign up</Button>
</form>
</div>
</section>
<?php
include_once 'footer.php';
?>
I have reset the password for 'root' to 'root' and ensured I can login with that. The document that checks for error's lists if any field is empty, return to the previous page with the word "=empty" in the url. No matter what I type into my fields, it is either not pushing the information into the database or I have incorrectly mapped my fields so one of the database fields is empty.
Any help would be greatly appreciated. As I said at the beginning of this post, I am extremely new at this. You may see something that is incredibly obvious and somewhat dumb... you've been warned! I am working on creating a mobile application and website that allows users to login. The login attempt will reference my localhost database to confirm that the user does not exist or that the user is not in use.
Thank you!
To check the connection handling, you can add this after the connect attempt:
$conn = mysqli_connect( ... );
if ( !$conn ) {
die( 'Did not connect: ' . mysqli_connect_error() );
}
To check the handling after a query, you can add this after the query attempt:
$result = mysqli_query( $conn, $sql );
if (false === $result) {
die( 'Query error: ' . mysqli_error($conn) );
}
Using php -l right off the bat I found some errors in your code in the includes/signup.inc.php file.
The line echo <h2>Please fill in all fields; was not quoted which would cause an error 500 when I tried to load the page. To fix this I added single quotes echo '<h2>Please fill in all fields</h2>'; and added </h2> to close the HTML tag.
After that was fixed the page would return Please fill in all fields even though I had filled all the fields in the sign up form. to fix this issue I changed mysqli_real_escape_string($conn, $_POST['POST_DATA']); to strip_tags(trim($_POST['POST_DATA']));.
The email line is a little bit different, mysqli_real_escape_string($conn, $_POST['email']); is changed to filter_var(trim($_POST['email'], FILTER_SANITIZE_EMAIL));
I also changed the $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT); (PHP Documentation: http://php.net/manual/en/function.password-hash.php) line to add salt. What is salt?
In cryptography, a salt is random data that is used as an additional
input to a one-way function that "hashes" a password or passphrase.
Salts are closely related to the concept of nonce. The primary
function of salts is to defend against dictionary attacks or against
its hashed equivalent, a pre-computed rainbow table attack.
Source: en.wikipedia.org/wiki/Salt_(cryptography)
Also take a look at this post in stackexchange/security for some more information Link: https://security.stackexchange.com/a/51983
New includes/signup.inc.php file
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = strip_tags(trim($_POST['first']));
$last = strip_tags(trim($_POST['last']));
$email = filter_var(trim($_POST['email'], FILTER_SANITIZE_EMAIL));
$uid = strip_tags(trim($_POST['uid']));
$pwd = strip_tags(trim($_POST['pwd']));
//Error handlers
//Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($uid) || empty($pwd)) {
echo '<h2>Please fill in all fields</h2>'; // was echo <h2>Please fill in all fields; which would cause an error 500
exit ();
}
else {
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
header("Location: ../signup.php?signup=invalid");
exit();
}
else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=email");
exit();
}
else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
}
else {
//Hashing the password
$options = [
'cost' => 12,
];
$hashedPwd = password_hash($password, PASSWORD_BCRYPT, $options); // Adding salt to hashed password
//Insert the user into the database
$sql = "
INSERT INTO users (first, last, email, uid, pwd)
VALUES ('" . $first . "',
'" . $last . "',
'" . $email . "',
'" . $uid . "',
'" . $hashedPwd . "');";
mysqli_query($conn, $sql);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
}
else {
header("Location: ../signup.php");
exit();
}
?>
In addition it would be a good idea to learn how to use the OOP style of mysqli to do more complex database manipulation
PHP Documentation on mysqli: php.net/manual/en/mysqli.query.php
It would also be good to add a column to act as a serial number to allow later editing of values for the users using this MySQL Query:
ALTER TABLE `users` ADD `serial` INT PRIMARY KEY AUTO_INCREMENT;

Check if email already exists in database and add/change data

I've got a form which has 14 numeric inputs and 2 text inputs - name and email. Someone is adding data and it's saved to the database - I've done it. But when someone is adding data for the second time using the same email address, database should override the data in specific row with that email.
I read about UPDATE in sql but I don't know how to make a query which will check if that email exists and after that add or update data.
<?php
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "test";
$quantity = $_POST['quantity'];
$quantity2 = $_POST['quantity2'];
$quantity3 = $_POST['quantity3'];
$quantity4 = $_POST['quantity4'];
$quantity5 = $_POST['quantity5'];
$quantity6 = $_POST['quantity6'];
$quantity7 = $_POST['quantity7'];
$quantity8 = $_POST['quantity8'];
$quantity9 = $_POST['quantity9'];
$quantity10 = $_POST['quantity10'];
$quantity11 = $_POST['quantity11'];
$quantity12 = $_POST['quantity12'];
$quantity13 = $_POST['quantity13'];
$quantity14 = $_POST['quantity14'];
$name = $_POST['name'];
$email = $_POST['email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Results (1paracwierc, 1paracwierc2, 2paracwierc, 2paracwierc2, 3paracwierc, 3paracwierc2, 4paracwierc, 4paracwierc2, 1parapol, 1parapol2, 2parapol, 2parapol2, final, final2, name, email)
VALUES ($quantity, $quantity2, $quantity3, $quantity4, $quantity5, $quantity6, $quantity7, $quantity8, $quantity9, $quantity10, $quantity11, $quantity12, $quantity13, $quantity14, '$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "Saved.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Use insert . . . on duplicate key update. You can do this if you have a unique key on what you want to be unique:
create unique index idx_results_name_email (name, email);
Then, the database will enforce uniqueness. The statement you want is:
INSERT INTO Results (1paracwierc, 1paracwierc2, 2paracwierc, 2paracwierc2, 3paracwierc, 3paracwierc2, 4paracwierc, 4paracwierc2, 1parapol, 1parapol2, 2parapol, 2parapol2, final, final2, name, email)
VALUES ($quantity, $quantity2, $quantity3, $quantity4, $quantity5, $quantity6, $quantity7, $quantity8, $quantity9, $quantity10, $quantity11, $quantity12, $quantity13, $quantity14, '$name', '$email')
ON DUPLICATE KEY UPDATE 1paracwierc = VALUES(1paracwierc),
1paracwierc2 = VALUES(1paracwierc2),
. . .
final2 = VALUES(final2);

Inserting a table in a database without knowing prefix

I have a small script that will insert two tables in a database, which works fine unless the user has changed the default prefix. I am wondering how I can call and use the "prefix" from the config file. Here is my code.
<?php
include("../../Config/config.php");
$link = mysql_connect($CONFIG['host'], $CONFIG['login'], $CONFIG['password'];
$db = ($CONFIG['database']);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$db", $link);
$sql = 'INSERT INTO settings '.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';
$exec = mysql_query($sql, $link);
if (!$exec) die(mysql_error());
mysql_close($link);
?>
You can see that I call "config.php" to get the database info. That would also work to get the prefix but I'm not sure how to implement the "prefix" with the rest of the code.
FYI: I'm a newbie :)
Thanks.
I got it, here's what worked.
<?php
require_once ("../../Config/config.php");
$link = mysql_connect($CONFIG['host'], $CONFIG['login'],$CONFIG['password']);
$table_prefix = ($CONFIG['prefix']);
$db = ($CONFIG['database']);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$db", $link);
$sql = 'INSERT INTO ' . $table_prefix . 'settings'.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';
$exec = mysql_query($sql, $link);
if (!$exec) die(mysql_error());
mysql_close($link);
?>
Thanks for the help BK435
Welcome!
I am assuming you can get the prefix and store it in variable. When calling your sql add this to your code ' . $TABLE_PREFIX . '. so your above insert would look something like:
$sql = 'INSERT INTO ' . $TABLE_PREFIX . 'settings '.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';

Displaying MYSQL data in a HTML table AFTER a search

I want to thank everyone here for the help I have recieved so far. My next question is a bit more complicated.
So I have a database set up on my server, and I have a form on my website where I am submitting data to my MYSQL database.
After I submit the data, I am having trouble searching for it, displaying possible results, and then making those results HYPERLINKED so that the user can find out more about they are looking for.
My "common.php" script is set up like this:
<?php
$username = "XXX";
$password = "XXX";
$hostname = "XXX"; 
$database = "XXX";
mysql_connect($hostname, $username, $password, $database) or die
("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>��
My "insertdata.php" script is set up like this:
<?php
require("common.php");
// connect with form
$name=$_POST['firstname'];
$lastname=$_POST['lastname'];
$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$various=$_POST['various'];
$other=$_POST['other'];
// insert data into mysql
$query="INSERT INTO datatable
(
firstname,
lastname,
city,
state,
zip,
phone,
email,
various,
other,
)
VALUES
(
'$firstname',
'$lastname',
'$city',
'$state',
'$zip',
'$phone',
'$email',
'$various',
'$other',
)";
$result=mysql_query($query);
// if successfull displays message "Data was successfully inserted into the database".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR... data was not successfully insert into the database";
}
mysql_close();
?>��
From there, I want to make the inserted data searchable.
My problem is, when the search is completed, I want to only display the First Name and Last Name in two separate columns.
From there, I want a link displayed in a third separate column with a link in each row that says "View Record Details."
Finally, when "View Record Details" in clicked, it brings me to the correct record, formatted again in an HTML table.
The closest I have come to a solution is:
<?php
require("common.php");
$query="SELECT * FROM datatable";
$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$firstname=mysql_result($result,$i,"firstame");
$lastname=mysql_result($result,$i,"lastname");
$i++;}
?>
As an additional question, when I use PDO, does that change my HTML?
Switch to PDO. Your code will look something like this:
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$sql = 'SELECT * FROM datatable';
foreach ($conn->query($sql) as $row) {
print $row['firstname'] . "\t";
print $row['lastname'] . "\n";
}
EDIT:
To link back for details add this line after the 2nd print:
print "<a href='somephp.php?idx=" . $row[ 'idx' ] . "'>link here</a>";
You'll need another php file called 'somephp.php':
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$idx = $_REQUEST[ 'idx' ];
$sql = 'SELECT * FROM datatable where idx = ?';
$stmt = $conn->prepare( $sql );
$stmt->bindParam( 1, $idx );
$stmt->execute();
$row = $stmt->fetch();
// now print all the values...
print $row['firstname'] . "\t";
print $row['lastname'] . "\t";
print $row['address'] . "\t";
and so on...
NOTE: This depends on each record having a unique key 'idx'. I don't see this in your values above so you'll have to find a way to incorporate it if you want to use this code.
ALSO: You ask - does this change the HTML and does this handle table formatting - No to both. You do all the HTML formatting via the print statements. All PHP does it output lines to the browser.