My data is not being stored in my database - php

I can't seem to figure out what is wrong with my code. I am trying to get it to take the input from
<form id="contact-form" action="emails.php" method="post">
<input placeholder="Please enter your email address" name="emailz" type="email" tabindex="2" required>
<input type="submit" name="submit" id="contact-submit" value="Subscribe">
</form>
and have it saved into my database.
Here is my PHP file:
$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$insert = "INSERT INTO emails(addressEmail) VALUES($_POST '$emailz')";
$conn->close();

To use MySQLi in a safe way, it's best to use Prepared Statements. This will prevent your users from inserting SQL injection or, possibly by mistake, inserting characters that can cause problems to your MySQL server.
As you can see in the script below, I'm first preparing the SQL query, using a placeholder "?" for the item variable. After I'm binding the parameter(variable) to this placeholder.
Now the query is setup correctly, it's time to execute it. It's always a good habit to close anything left open once done, as it will free up memory that's no longer in use.
<?php
/* DB Info */
$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";
/* MySQLi Object */
$conn = new mysqli($servername, $username, $password, $dbname);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Prepare query */
if ($stmt = $conn->prepare("INSERT INTO emails (addressEmail) VALUES (?)")){
/* Bind POST data */
$stmt->bind_param("s", $_POST['emailz']);
/* Run query */
$stmt->execute();
/* Close statement */
$stmt->close();
}
/* Close connection */
$conn->close();
?>

Here is how you do the insert -
$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO `emails`(`addressEmail`) VALUES(?)");
$stmt->bind_param('s', $email);
$email = $_POST('emailz');
$stmt->execute();
First you prepare the query and leave placeholders for the item variables. The you bind each parameter(variable) and then declare them. Finally you execute the query.

First check if the user hasn't missed anything:
if (isset($_POST['emailz']) { //code here.. };
In the code here... section, store the value of emailz in a variable like this:
$emailz = $_POST['emailz'];
Of course this may be insecure for more important data like passwords. You should use the hash() function then.
For inserting the variable in DB, try this:
$query = "INSERT INTO `user` (emailz) VALUES ('$emailz')"; $result = mysql_query($query); //inserts the variable in the DB.

Related

Check if a MySql database has been updated in PHP

I am trying to detect whether a MySql database has been updated the second it has been updated. So far I've just found triggers but it, https://www.siteground.com/kb/mysql-triggers-use/, said I need superuser privileges and, unfortunately, the domain I use is a shared server.
So currently there is one group working on inserting all user information into the database like so.
<form method="post">
-> user post data
</form>
<?php
-> post data to varibles, $x $y as examples
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "name";
// Check connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO Test (Col1, Col2)
VALUES (". $x .",". $y .")";
mysqli_close($conn);
?>
And then my group, in a separate file, is supposed to get the data from the database when it is updated. Our file set up looks like this.
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "name";
// Check connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
->trigger on column update
$sql = "SELECT Col1, Col2, time FROM Test";
$result = mysqli_query($conn, $sql);
->etc.
mysqli_close($conn);
?>
So far I've only found triggers that are in MySql but there doesn't seem to be a way to directly do it in PHP ex.
mysql> CREATE TRIGGER agecheck BEFORE INSERT ON people FOR EACH ROW;

PHP form doesn't insert into SQL database

I am trying to test a very simple PHP form that inserts input into an SQL database. The connection works fine, but the data does not appear in the database when I refresh it. I have only two files, an index.html and a process.php.
index.html:
<html>
<head>Testing</head>
<body>
<div id="frm">
<form action="process.php" method=POST>
<p>
<label>Username</label>
<input type="text" id="stuff" name="stuff">
</p>
<p>
<input type="submit" id="btn" value="Login">
</p>
</form>
</div>
</body>
</html>
Process.php:
<?php
$userinput = $_POST['stuff'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "testing";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error)
{
die("connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully ";
echo $userinput;
$sql = "INSERT INTO `entries`(`input`) VALUES ('$userinput')";
}
?>
The problem is that you're not actually running the query. You just assigned the query string to a variable, so it's not being executed in MySQL.
Your code is vulnerable to SQL injection, so I'm proposing a solution:
<?php
$userinput = $_POST['stuff'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "testing";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error)
{
die("connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully ";
echo $userinput;
$sql = "INSERT INTO `entries` (`input`) VALUES (?)";
if ($stmt = $conn->prepare($sql)) { // Prepare statement
$stmt->bind_param("s", $userinput); //Bind the string (s), with the content from $userinput to the statement marker (?)
$stmt->execute(); // Run (execute) the query
$stmt->close(); //clean up
}
This code should work and also keep you secure from SQL injections.
Haven't tested it fully but I fixed your query.
$sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");
also change the post part to: <form action="process.php" method="POST">
That should fix the problem for you
Also make sure you use the function: mysqli_real_escape_string to escape malicious user input to prevent SQL injection.
Another thing: you could change localhost to 127.0.0.1. I think this is more reliable although it's the same in most cases.
Your code is not submitting the query to the database, it is opening the connection but not submitting the query, see below to the submit query request if you use mysqli in PHP
... else {
# this submits the query
$conn -> query ($sql);
}
you need to take function mysqli_query of mysqli that will take parameter as connection object like $conn and 2nd parameter will be sql query to execute.
like this
$sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");
to prevent from sql injection you must use PDO because PDO use paramBind to protect injection .

Why isn't my PHP connecting to my database or displaying an error?

I am creating a form that will take a person's name and email and see if the email exists in the database already but I can't get the database to be selected. The mysql_error() won't display the error either. Is there something wrong with my code for selecting the database? All it shows is the hardcoded text "Could not select database because" then nothing. I replaced all the variables associated with the database with random fillers so as not to give away my info but everything I have is correct regarding that.
$host = "host";
$user = "user";
$password = "pass";
$database = "db";
$port = xxxx;
$table = "table";
// Create connection
$conn = mysqli_connect($host, $user, $password, $database, $port);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection Successful";
mysqli_select_db($database)
or die("Could not select database because".mysqli_error());
// check if the username is taken
$check = "select email from $table where email = '".$_POST['email']."';";
$qry = mysqli_query($check)
or die ("Could not match data because ".mysqli_error());
$num_rows = mysqli_num_rows($qry);
if ($num_rows != 0) {
echo "Sorry, there the username $username is already taken.";
}
Don't call mysqli_select_db. You've already selected your database with the fourth parameter to mysqli_connect.
You only need to call mysqli_select_db if you want to access a different database after the connection has been established.
Also, Raptor is correct that if you call procedural mysqli_error() you must pass it a connection handle.
For Procedural style mysqli_error(), you must supply the MySQLi DB link as parameter:
mysqli_select_db($database)
or die("Could not select database because" . mysqli_error($conn));
But it's useless to call mysqli_select_db() as you already specified the DB schema in mysqli_connect().
Additionally, your SQL is vulnerable to SQL Injection attack. Always escape the parameter before putting into SQL statement, or use prepared statements.
try this code
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>

php store session variable in mysql database

I have a website in PHP. I try to store the session variable $_SESSION['user_name'] to a mysql database when a logged in user visits a specific webpage on my site.
<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users
VALUES ('.$_SESSION['user_name'].')';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Error message:
Notice: Undefined variable: _SESSION in /opt/lampp/htdocs/succes.php on line 16
Tried a bunch of things but can't figure it out. What is wrong here?
You need to call session_start() at the beginning of your script (before using any $_SESSION variables). Also, you need quotes around the variable in you query:
$sql = 'INSERT INTO users
VALUES ("'.$_SESSION['user_name'].'")';
Please note that this is not safe; you are wide open to SQL injection. Instead, you should use prepared statements:
<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users
VALUES (?)';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $_SESSION['user_name']);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Before you use any $_SESSION variables you need to call session_start().
Of topic a bit though, something to look into PDO. It can be a bit a tad slower than mysqli() however supports many more Database types. Here is a good article on Tuts+ explaining some of the differences as well as explaining essential security steps.
If I could be a bit biased I have created a PHP Class for PDO Connections which can be found on GitHub

How to extract desired row from Mysql database using PHP script

I have created one HTML form which takes input from user ,Now I need to search user inputed name in Mysql database and print details related to that user inputed name which is stored in Mysql database.
Below script is creating HTML form to take user input, Saved as "ProcessTracking.html".
<form action="details.php" method="get"/>
<h3 align="center"><FONT color=#CCFF66>ENTER SO NUMBER</h3>
<p align="center">
<input type="text" id="SO_Number" name="SO_Number"/>
</p>
<div style="text-align:center">
<button type="submit" value="SEARCH">
<img alt="ok" src=
"http://www.blueprintcss.org/blueprint/plugins/buttons/icons/tick.png"/>
SEARCH
</button>
</form>
Below PHP script named as "details.php"
<?php
$userinput = $_GET['SO_Number'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE SO_Number = '$userinput'") or die(mysqli_error($conn));
$row = mysqli_fetch_assoc($result);
#printf ("SO_Number: %s \n",$row["SO_Number"])
#print_r($row);
printf ("SO_Number:");
printf($row["SO_Number"]);
printf ('--||--');
printf ("Name:");
printf($row["Name"]);
printf ('--||--');
$conn->close();
?>
Firstlly you are not using the $_GET['SO_Number'] parameter in a WHERE of SQL statement. Secondlly you are using both mysql and mysqli which are totaly diffrent and don't work together. For usage see mysqli_fetch_row() and mysqli_query(). Also use print_r($row);.
Here is the corrected code:
<?php
$userinput = $_GET['SO_Number'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE SO_Number = '$userinput'") or die(mysqli_error($conn));
$row = mysqli_fetch_row($result);
print_r($row);
$conn->close();
?>
EDIT: Added code example.
You have mixed mysql and mysqli api together. Try using either one.
Note: mysql api is deprectaed as of php 5.5.0
1st Error
As saty says it is because of the syntax error you have in this line
print_r"$row";
which should be as print_r($row)
2nd Error
You're mixing mysql & mysqli
I am not sure about the table that you have.
Recommendation :
I would recommend you to turn on the error_reporting if not those errors will be in your errors_log file
Also for debugging your sql, you can first construct your sql query, run in the phpmyadmin or related tools for your query, then fire the query and make this done.
Note :
If you are using these code in online then the error_log will be in the directory where you execute this page. (But it may change according to your hosting)
If you are running in local machine the error log may locate according to the server you use...
You can find by printing the php's configuration by phpinfo and find for
error_log
May this thing will fix your issue
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
$so = $_POST['SO_Number'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT * FROM ProcessDetails WHERE SO_Number=$so");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row[SO_Number]);
$conn->close();
?>

Categories