MySQL connection doesn't work Ubuntu? - php

I have installed lamp on Ubuntu and everything is working fine i tried localhost/testphp() that works fine but when I put that code it shows the values if i echo them but it doesnt insert them in the db and it doesnt give error on mysql connection either.
using POST method to send form data
<form action="form.php" method="POST">
<label>Email:</label>
<input type="text" name="name">
<label>Password</label>
<input type="password" name="pass">
</form>
and here is the php code
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
echo "hello I am here !<br/>";
$con=mysqli_connect("localhost","root","123","login");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = $_POST['name'];
$password = $_POST['pass'];
echo " Name: ".$name." <br/>Password: ".$password;
mysqli_query($con,"INSERT INTO login_data (username, password) VALUES ('". $name ."', '". $password ."')");
//it doesnt insert the data
//how do i check the error of that query ?
mysqli_close($con);
?>
Help !

$sql="INSERT INTO login_data(username,password) values(".$_POST['name'].",".$_POST['password'].")";
mysqli_query( mysqli $link , string $query)
First connection, then the query. And use mysqli
$a=mysqli_query($con, $sql );

First of all you can enable PHP errors with your php.ini with :
display_errors = on
Or by using a .htaccess file.
Then the sql may be :
$sql = "INSERT INTO login_data(username, password) VALUES ('". $name ."', '". $password ."')";
As Don said, you use mysqli and then mysql. You have to use mysqli_query();

your sql statement is incorrect :
$sql="Insert into login_data(username,password) values("$name","$password")";
It should be
$sql="Insert into login_data(username,password) values("'".$name."'","'".$password."'")";
since $name and $password are predefined, you just need to pass them with proper quotes.

Related

PHP Not Posting in SQL Database Insert Statement

So I'm attempting to gather data from a form in HTMl using the POST method and insert said data into a MySQL database using MySQLi functions. When in standalone PHP (without the database connection), I'm able to POST and echo data successfully to the second document.
However, once I open the connection to the database and attempt to use an insert statement, the data stops POSTing all together. I've tested the insert statement using strings, it works just fine.
Here's my form:
<form action="welcome" method="post">
First Name*<br>
<input type="text" name="userFN" required><br><br>
Last Name*<br>
<input type="text" name="userLN" required><br><br>
Email*<br>
<input type="email" name="userEmailAddress" required><br><br>
Password*<br>
<input type="password" name="userPassword" required><br><br>
Tell Us About Yourself<br>
<textarea rows="4" cols="50" name="userDescription">
</textarea>
<br>
<input type="submit">
</form>
Here's my PHP (welcome, as used in the action above).
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//post form info into variables
$userFN = mysqli_real_escape_string($conn, $_POST['userFN']);
$userLN = mysqli_real_escape_string($conn, $_POST['userLN']);
$userEmailAddress = mysqli_real_escape_string($conn, $_POST['userEmailAddress']);
$userPassword = mysqli_real_escape_string($conn, $_POST['userPassword']);
$userDescription = mysqli_real_escape_string($conn, $_POST['userDescription']);
$sql = "INSERT INTO users (userFN, userLN, userEmailAddress, userPassword, userDescription) VALUES" . " ('" . $userFN . "','" . $userLN . "','" . $userEmailAddress . "','" . $userPassword . "','" . $userDescription . "');";
echo $sql;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
It always returns New record created successfully, and inserts a new record into the database, but all of the fields are blank. When I echo the insert statement, I get this:
INSERT INTO users (userFN, userLN, userEmailAddress, userPassword, userDescription) VALUES ('','','','','');
So it's clearly not getting my POST data anymore. I've tried using prepared statements and still no luck. What am I doing wrong here? I greatly appreciate any and all advice, thank you in advance.
The answer may surprise you.
So the issue is actually in the form "action". Because of the way my webhosting provider is configured, I actually needed to specify /index.php/ after the folder name in the action. It was actually confusing the server and for some reason translated to 'GET' instead of 'POST'. Hope this helps.
Thanks for all the support!

php script to write to SQL database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am new to php and have written the following php script to write from a FORM. However, the database is not updating. I know that the database connection is okay. Any help would be appreciated.
$name = $_POST["name"];
$lastName = $_POST["last_name"];
$email = $_POST["email"];
$location = $_POST["location"];
$timestamp = date("Y-m-d H:i:s");
$sql = "INSERT INTO club.users (name, last_name, email, location, created_at) VALUES ('$name', '$lastName', '$email', '$location', '$timestamp')";
Try this
You have to use the SQL injection for security something like this
$conn->real_escape_string($_POST['name']);
Check your table name.I haven't use table name club.users before because it will display the error like table does't exist. Just use the table name club or users
Time to learn the PHP
https://www.w3schools.com/php/php_mysql_insert.asp
index.php
I hope your HTML code looks like this
<form action="register.php" method="POST" name="register">
<input type="text" name="name" placeholder="Name">
<input type="text" name="lastname" placeholder="Lastname">
<input type="email" name="email" placeholder="Email">
<input type="text" name="location" placeholder="Location">
<input type="submit" name="submit" value="Register">
</form>
Connection.php
If you are working on the local server the used root as username and password should be blank.
$servername = "localhost";
$username = "root";//if you are working on local server
$password = ""; //set blank if you are working on local server
$dbname = "myDB";//your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
register.php
<?php
include('connection.php');// added the connection here
if (isset($_POST['submit'])) {
$name = $conn->real_escape_string($_POST["name"]);
$lastName = $conn->real_escape_string($_POST["lastname"]);
$email =$conn->real_escape_string($_POST["email"]);
$location = $conn->real_escape_string($_POST["location"]);
$timestamp = date("Y-m-d H:i:s");
$sql = "INSERT INTO club (name, lastname, email, location, created_at) VALUES ('$name', '$lastName', '$email', '$location', '$timestamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
First of all define the db server connection in same php page or you may include the connection. Php file for this purpose.
Secondly it you wish to use MySQL db simple use musql_query($sql, $con) then write below lines of after inserting results.
Sorry I posted it from my mobile if you need I can post you entire code sample from my PC.

Correction on Inserting data into SQL Table via PHP

I've been using php and mysql for my computing project and I've just run into this small problem. I've tried countless numbers of variations to this line of code but I always seem to receive an SQL Error.
Background Information:
HTML Document that contains a form, allowing the Admin to upload an image path, a name for the photo and a comment as well
PHP Document containing SQL that runs the code for this. I've worked out how to insert either an image path, a name or a comment but not all three at once...
Here's the line of code that causes the problem, specifically inserting the data into the database.
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('{$_POST{[ VALUES GO HERE, WHAT SYNTAX/HOW??? ]}')";
The HTML Form is here (for anyone interested):
<form action="insertTest.php" method="POST" enctype="multipart/form-data">
Image: <input type="text" name="image" /><br>
Name: <input type="text" name="name" /><br>
Comment: <input type="text" name="comment" /><br>
<input type="submit">
</form>
PHP Doc (whole upload file, quite small, changed password for security xD):
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "admin_db";
// Create connection
$conn = new mysqli($servername = "localhost", $username = "root", $password = "password", $dbname = "admin_db");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('{$_POST{[]}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
$image = $_POST['image'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('$image', '$name', '$comment')";
you can set variables to the associative array (with name from html form) and include each in the sql query. Something like this:
$image = $_POST['image'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('$image','$name','$comment')";
Separate your variables $imgpath=$_POST["path"]; $imgname=$_POST["name"]; $imgcomment=$_POST["comment"]; now insert into table.... INSERT INTO imgtable(path,name,comment) VALUES('$imgpath','$imgname','$imgcomment')

PHP not inserting into tables

I'm having trouble getting a practice signup form to submit data to my database ...
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$name = $email = $password = "";
?>
<form method="post">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Password: <input type="text" name="password">
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
function fix_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
In addition to Ugur's answer, you are mismatching mysqli commands and mysql commands. Here's how to do this in an object oriented fashion:
// create mysqli database object
$mysqli = new mysqli_connect("localhost","username","password","database");
// store your query in a variable. question marks are filled by variables
$sql = "INSERT INTO table_name ('username','password') VALUES (?,?)";
// prepare command uses $sql variable as query
$stmt = mysqli->prepare($sql);
// "ss" means your 2 variables are strings, then you pass your two variables.
$stmt->bind_param("ss",$name,md5($password));
// execute does as it seems, executes the query.
$stmt->execute();
// then print your success message here.
Using prepared statements removes the need to sanitize user input, as harmful input is not substituted into the query directly. For more reading:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
There are some good tips for using prepared statements in many different scenarios, as well as towards the bottom, there is an explanation on how prepared statements prevent SQL injection.
Missing table name
mysql_query("INSERT INTO ...... ('username','password') VALUES ('$name', md5('$password'))");
You're mixing mysql_* with mysqli_* functions, i.e.: mysqli_connect and mysql_query and you're wrapping your column names in quotes, plus you're missing the table name to insert into.
Try the following, fixed code:
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysqli_query("INSERT INTO `your_table` (`username`,`password`) VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
You're also using password storage technology that dates back to 1996. MD5 is no longer considered safe to use.
I suggest you look into PHP's password function: http://php.net/password
And if you're having problems with your fix_input() function, you should consider using the mysqli_real_escape_string() function.
then setting up a DB connection while passing a variable to it.
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
and instead of using:
$name = fix_input($_POST["name"]);
use the following:
$name= mysqli_real_escape_string($db, $_POST['name']);
and do the same for the rest.
you don't have table name in your query! also do not use quotation in your column name :)
you have mixed up mysqli and mysql.
Change
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
to
mysqli_query("INSERT INTO yoour_table(username',password) VALUES ('$name', md5('$password'))");

I cant get the form data to go into database. What am I doing wrong?

CODE UPDATED, STILL NOT WORKING.
I know I´m apparently using mysql function which will be outdated. But for now all I want is for this code to work. I want to know what I´m doing wrong:(
I´m very new to php and databases... I have been struggling to get simple html form data to go into the database table. And I just can´t get it to work:( Can anyone help and see what is wrong with my code? I´ve just done a simple table in the database with the fields ID, FIRSTNAME and SURNAME.
Here is the code:
<?php
//connect to database
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';
$mysql_db = 'test';
if (!mysql_connect ($mysql_host, $mysql_user, $mysql_pass)||!mysql_select_db ($mysql_db) ) {
die(mysql_error());
}
// Code
if (isset($_POST['firstname'])&&
isset($_POST['surname'])) {
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
if (!empty($username)&&!empty($password)) {
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
/*$query = "INSERT INTO `test`.`test_tabell` VALUES (``, `.$firstname.`, `.$surname.`)"; */
$query_run = mysql_query($query);
if (!$query_run) echo mysql_error();
}
}
?>
<form action="add.php" method="POST">
Firstname:<br> <input type="text" name="firstname" value="<?php if (isset($firstname)) { echo $firstname; } ?>"><br><br>
Surname:<br> <input type="text" name="surname" value="<?php if (isset($surname)) { echo $surname; } ?>"><br><br>
<input type="submit" value="Submit">
</form>
Thank you!
Don't use mysql specific syntax, It's outdated and it begins to be annoying when you need to do some high level stuff, and you can't switch to sqlite or postgresql.
I recommend using PDO, you can do something like:
// Usage: $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables (I think you forgot to define the name of the database);
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$GLOBALS['db'] = connectToDataBase($host , $databaseName, $user, $pass);
Now you have an instance of a PDO database donnection.
One thing I want to point out is that you're vonurable to sql injections, you want to use prepared statements in your query, like:
$query = "INSERT INTO test(first_name, sur_name) VALUES (:firstname, :surname);";
Where we will execute two variables $firstName and $surName on the query, making them replace the values of :firstName and :surName, let me show you by first creating a simple insertion function:
function insertFunction($db, $query, $firstName, $surName)
{
$statement = $db->prepare($query);
return $statement->execute(array(":firstName" => $firstName, ":surName" => $surName));
}
So It's easy for you to do something like
$firstName = 'Smith';
$surName = 'John';
$db = $GLOBALS['db'];
$success = insertFunction($db, $query, $firstName, $surName);
Now you can check if it was successful or not, by checking whether $success is true or false.
If you want to see more advanced use of PDO (multiple rows etc) then you can check out one of my comments here: Javascript function as php?
(Not the top comment).
I hope this helps. Please comment if anything is odd.
Hard to tell without seeing your schema but try this:
$query = "INSERT INTO `test`.`test_tabell` VALUES ('', '$firstname', '$surname')";
$query_run = mysql_query($query);
You're using backticks instead of apostrophes. Also, you're trying to execute a query before defining what the query is.
Your insert query is wrong and also open to SQL injections. Here's how it should be:
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
Notice the changing of all backticks to apostrophe.
Also, you're trying to execute the query before defining it.
EDIT
As per your information related to table definition, you can skip the id field from your table. The INSERT query will become:
$query = "INSERT INTO `test`.`test_tabell` (`FIRSTNAME`, `SURNAME`)
VALUES ('" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
$query_run = mysql_query( $query );
As posted in the comments, you REALLY SHOULD NOT use/learn/practice using any function that starts with "mysql_" since it will NOT work as soon as PHP is updated. These functions are on their way out. Best of luck with learning to use PHP and SQL databases - just make sure you're learning something that will be useful in the future. Make sure to read up on Object Oriented Programming (OOP) in relation to PHP and both the PDO and mysqli_* functions.

Categories