how to add name number email id to my mysql database - mysql

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();
?>

Related

How to make reference to one of my MySQL databases inside my PHP file?

I have already asked this related question: https://webmasters.stackexchange.com/questions/116055/using-mysql-database-data-directly-into-generating-articles-for-my-website-new/116056?noredirect=1#comment154341_116056
At this point, I'm starting to understand the code syntax and project structure a little better.
But I have made my database using MySQL console. it only has a few entries so far, I wanted to try to adapt the code in Zach's example, but here is the problem I have:
The problem is, I am unsure how to get the reference to my database object? In the code sample from Zach there is variable $db, I guess this is where i need to keep a reference to my own actual database.
Here is the psuedo-code (maybe) from Zach, note: he always said to me not to copy-paste it, but I'm just trying to see how I can use it in my project.
<?php
$SQL_Query = "SELECT * FROM your_table";
$SQL_Run = mysqli_query($db, $SQL_Query);
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
?>
So my question simply at moment is: How to create the reference $db?
Your answer is the correct way to establish a connection. I want to point out that there are two ways of writing that statement. The version you found online is one way, but from our previous conversation, you can write it like this:
<?php
// Establish how to log in
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// create the database connection
$db = new mysqli($servername, $username, $password, $dbname);
// if it fails, kill the site.
if (mysqli_connect_error($db)) {
die("Connection failed: " . mysqli_connect_error($db));
}
// your first query to grab all the article data
$SQL_Query = "SELECT * FROM your_table";
// run the query
$SQL_Run = mysqli_query($db, $SQL_Query);
// while data exists (it makes sure that you have post data, otherwise nothing shows up)
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
// Close the connection
mysqli_close($db);
?>
You will notice that the connections are written like a function.
mysqli_num_rows($result);
instead of
$result->num_rows
Both do the same thing, just a personal preference. That should hopefully clear some things up from your first post :)
I have got further on and I think have answered my own question. I found it a bit tricky to research because I don't understand all the different terms and names of features/api/scripts/etc. But I had just to read the documentation for mysqli_connect(), I set up the code as follows and now I have pulled all the data from the database into words on my html/php files.
From here I think I can rewrite the code to first sort it by date and then can of course put the latest posts at the top of each page etc.
I can also allow the user to click 'Genre' and only view Comedy for example.
Here is the code just to get the data parsed into my index.php file:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, type, title FROM releases";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Type: " . $row["type"]. " - Title " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I extended upon the above work by making the php script fetch all the entries in the database and create the previous html article I had once for each entry. In the SELECT statement I can control which types of entries are displayed (eg. For a certain category). Here was how I did it:
// make an html article based snippet (image, title, description, etc),
//once for each entry in the database table...
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "somepassword";
$dbname = "somedatabasename";
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM releases ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo '<section class="wrapper style1">';
echo '<div class="inner">';
echo '<header class="align-center">';
echo '<h2>'. $row["title"] . '</h2>';
echo '<div class="image fit">';
echo '<img src='. $row["imgurl"] .'>';
echo '</div> <p> RELEASE TITLE: ' . $row["title"] . '<br /> DATE POSTED: ' . $row["postdate"] . '<br /> DESCRIPTION: ' . $row["description"] . '</p>';
echo 'DOWNLOAD LINK: '.$row["link"].' <br />';
$NfoLink = $row["nfolink"];
if ($NfoLink != 'not found' && $NfoLink != '')
{
echo 'NFO LINK/MORE DOWNLOADS: '.$row["nfolink"].'';
}
echo '</header>';
echo '</div>';
echo '</section>';
}
}
else
{
echo "0 results";
}
$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);

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.

I was looking to see if someone could tell me how secure this is

I am writing a code that will check 2 different tables to determine the privileges the user will have. The code looks like this:
$query1 = ("SELECT 1 FROM `customers` WHERE `Email` = '$email' AND `Password` = '$password'");
$query2 = ("SELECT 1 FROM `admins` WHERE `Email` = '$email' AND `Password` = '$password'");
$result1 = mysql_query($query1) or die(mysql_error());
$result2 = mysql_query($query2) or die(mysql_error());
if (mysql_num_rows($result1) == 1) {
// Log user in as a Customer
exit;
} else if (mysql_num_rows($result2) == 1) {
// Log user in as an Admin.
exit;
} else {
// Direct user to registration page.
}
Can anyone look at this and tell me if there would be any security risk by doing it this way? Thank you in advance for your help!
Firstly you have a change that your code is only known by you.
Secondly you have to check the input data. email and password area is not safety. You should prevent SQL injection. Otherwise your code is not secure.
By the way i'm offering you IP restricted login for admins. I'm using this. And it is more secure.
One big problem here is that the code is vulnerable for sql injections.
Which basicly means that the user could put code in the email or password form to bypass the check you have here.
A start would be to perform the following to your input BEFORE you use them in your query:
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
Though, the mysql library is not recommended by php, rather read about prepared statements in pdo here: http://www.php.net/manual/en/ref.pdo-mysql.php
But you can try the mysql_real_escape_string to have a first security measure against sql injections.
This is insecure if for example my password was
OR 1=1
I get access. Use mysql prepared statements
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("SELECT 1 FROM customers WHERE Email = (?) AND Password = (?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("ss", $email, $password)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>