I'm starting to study php and mysql, I start with this simple module that include:
Create a Database connection; (run)
Connect to DataBase; (not give output message, probably not work)
Insert data; (not work)
Question:
Why it is not working correctly?
I create this simple PHP page (filename: inizio.php):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="it" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Pagina di inizio</title>
</head>
<body style="width: 672px; height: 289px">
<p class="auto-style1" style="width: 293px; height: 24px">Titolo centrato della pagina</p>
<form method="post" action="inserimento.php" style="width: 674px; height: 130px">
Inserisci il nome:<input name="nome" type="text" /><br />
Inserisci il cognome:<input name="cognome" type="text" /> <br />
<br />
<input name="Submit1" type="submit" value="Invia" /><br />
</form>
</body>
</html>
After I create this php script (filename inserimento.php):
<?php
$host='localhost';
$user='root';
$password='root';
$database='test_youtube';
// 1. Create a database connection
$connection = mysqli_connect($host,$user,$password);
if (!$connection)
{
die("Database connection failed: " . mysqli_error());
}
else
{
die("...Connesso con successo al Server!");
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, $database);
if (!$db_select)
{
die("Database selection failed: " . mysqli_error());
}
else
{
die("...Connesso con successo al Database!");
}
$query="insert into users(firstname, lastname)VALUES('".$_REQUEST['nome']."','".$request['cognome']."')";
if (!mysqli_query($query,$db_select))
{print("errore inserimento dati");
}
?>
Try die() like following in your php file:
$connection = mysqli_connect($host,$user,$password,$database);
/* check connection */
if (mysqli_connect_errno()) {
die("Connect failed: ", mysqli_connect_error());
}
$query="insert into users(firstname, lastname)VALUES('".$_REQUEST['nome']."','".$_REQUEST['cognome']."')";
if ($result = mysqli_query($connection ,$query))
{
print("Success!");
}
$con=mysqli_connect("localhost","root","root","test_youtube");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"INSERT INTO data_entry_users (user_name,user_password) VALUES ('".$_REQUEST['nome']."','".$_REQUEST['cognome']."')");
mysqli_close($con);
Related
I am trying to send the data put into the input fields to my database and I cant seem to make it work out properly..
The ultimate goal is to put in the input fields into the database and show the inserted data in another window.
Here's my code
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// create a variable
$naam=$_POST['namen'];
$plaats=$_POST['plaatsen'];
$land=$_POST['landen'];
//Execute the query
mysqli_query($conn,"INSERT INTO phptoets(Namen,Plaatsen,Landen)
VALUES('$naam','$plaats','$land')");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="POST">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
Try this. It will help you. I've done few changes in your code.
- Add form to post the data on server
- Add database name in connection
- Add provincie field in form (because you are trying to get that in php)
- Use the same variable in query as declared at the time of connection
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "DATABASE";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// create a variable
$namen=$_POST['naam'];
$plaatsen=$_POST['plaats'];
$landen=$_POST['land'];
$provincie=$_POST['provincie'];
//Execute the query
mysqli_query($conn, "INSERT INTO employees1(naam,plaats,land,provincie) VALUES('$namen','$plaatsen','$landen','$provincie')");
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="POST" action="">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="text" name="provience" class="input_provience" placeholder="Provience"><br>
<input type="button" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
This is my solution:
You forgot to set database name and the names of your input fields where not equal to your $_POST names.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// create a variable
$naam=$_POST['naam'];
$plaats=$_POST['plaats'];
$land=$_POST['land'];
//Execute the query
mysqli_query($conn,"INSERT INTO phptoets(namen,plaatsen,landen)
VALUES('$naam','$plaats','$land')");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="post">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
<?php
// TESTS
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br>";
if(isset($_POST['submit']))
{
// create a variable
$a = (string)filter_input(INPUT_POST,'naam');
$b = (string)filter_input(INPUT_POST,'plaats');
$c = (string)filter_input(INPUT_POST,'land');
$d = (string)filter_input(INPUT_POST,'provincie');
echo("executing query <br>");
//Execute the query
if($a != null && $b != null && $c != null && $c != null)
{
$sql="INSERT INTO employees1 (naam,plaats,land,provincie) VALUES (?,?,?,?)";
echo("sql ".$sql. "<br>");
if($stmt = $conn->prepare($sql))
{
$stmt->bind_param("ssss",$a,$b,$c,$d);
$stmt->execute();
$stmt->close();
}
}
$sql = "SELECT naam, plaats, land, provincie FROM employees1";
if ($stmt = $conn->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($naam,$plaats,$land,$provincie);
while ($stmt->fetch())
{
printf("naam : %s, plaats: %s, land: %s, provincie: %s <br>",$naam,$plaats,$land,$provincie);
}
$stmt->close();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<form class="my_form" target="_self" enctype="multipart/form-data" method="post">
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="text" name="provincie" class="input_land" placeholder="Provincie"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</form>
</div>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
I will just name few things that I changed in your code, not mentioning syntax errors
you dont specify db_name in your sql connection
you dont use prepared statements nor any kind of input filtering
(note : my input filtering is very basic, read more about how to
filter inputs)
to address html form you need to create one and have submit input
type inside
I am trying to make a web app, that searches by ID/Name input, Database A (client) for existing clients, IF the client exists display Database A(information data) and values on Database B (history of purchases from each client); if not it displays a form to add client to database A and after that add new purchase to database B.
So far this is my code:
index.php -> this is the search form:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form name = "inicio" action = "inicio.php">
Mostrar equipamento de:<input type="text" name="user" value="" />
<input type="submit" value="ir" />
</form>
</body>
</html>
this is the criteria for displaying Database info:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ola</title>
</head>
<body>
CLIENTES <?php //chama a ação de index.php
echo htmlentities($_GET["user"])."<br/>";?>
<?php
//declarar variaveis
$servername = "localhost";
$username = "phpuser";
$password = "phpuserpw";
$dbname = "equipamento";
$tablename = "clientes";
$user = "user";
//criar ligação
$conn = mysqli_connect($servername, $username, $password, $dbname);
//verifica licação
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//query
$sql = "SELECT ID, Nome FROM clientes WHERE Nome='" . $user . "'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) !== 0) {
//output data de cada fila
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["ID"]. " Nome: " .$row["Nome"]. "<br>";
}
}else {
echo "O cliente não existe";
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL); error_reporting(-1);
mysqli_close($conn);
?>
</body>
</html>
I believe the error reports to my query, but I am not experienced enough to understand what could be wrong.
Also, I have added error reporting script but it's not displaying any errors.
Where should it display?
Thanks for any help.
When I want to input some Chinese character into my form,
<html>
<title>
Form
</title>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
</head>
<body>
<div id="wrapper">
<form action="form.php" method="post" accept-charset="UTF-8" >
<p>Input: <input type="text" name="input1" /></p>
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>`
and the form.php:
<?php
header('Content-Type: text/html; charset=utf-8');
define('DB_NAME','form1');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_HOST','localhost');
$link= mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$link){
die('could not connect server'.mysql_error());
}
$db_selected = mysql_select_db(DB_NAME,$link);
if(!$db_selected){
die('Cannot connect'.DB_NAME.': '.mysql_error());
}
$value=$_POST['input1'];
$sql="INSERT INTO form (input1) VALUES ('$value')";
if (!mysql_query($sql)){
die('Error: '.mysql_error());
}
mysql_close();
header("Location: form.htm");
?>
Mysql sheet output something strange like 早਽
Why?
Should I do something on the code or on Mysql?
Please help!!!!
Thanks!!!!!!
Did you try to use this line after your database connection ?
mysql_query("SET NAMES utf8");
You can try this.
mysql_set_charset('utf8', $link);
Like this...
<?php
header('Content-Type: text/html; charset=utf-8');
define('DB_NAME','form1');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_HOST','localhost');
$link= mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_set_charset('utf8', $link);
if (!$link){
die('could not connect server'.mysql_error());
}
...
...
Please help, this is driving me mad! I have, I thought, a simple registration form that I am trying to send data with PHP to MySQL in Webmatrix. (PHP 5.5 to add data to MySQL 5.7 in webmatrix 3) however, I get the following error in Chrome:
The localhost page isn’t working
localhost is currently unable to handle this request.
500
Here's the PHP:
<?php
$db_user = 'root';
$db_pass = '';
$db_name = 'MySQL10';
$db_host = 'localhost';
$fname = $_POST('fname')
$lname = $_POST('lname')
$email = $_POST('email')
//Create Connection
$conn = new mysqli ( $db_host, $db_user, $db_pass, $db_name);
//Check connection
if ($conn->connect_error) {
die("Connection failed:" . $conn->connect_error);
}
$sql = "INSERT INTO table_1 (fname_1, lname_1, email_1)
VALUES ('$fname', '$lname', '$email')";
$conn->close();
?>
Here's Mark up:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test Page</title>
</head>
<body>
<div class="registration">
<form name="test" method="post" action="demo.php" autocomplete="on">
<p>First name:<input type="text" name="fname" value=""></p>
<p>Last name:<input type="text" name="lname" value=""></p>
<p>Email Address:<input type="email" name="email" value=""></p>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
thank you all. I added the [] and the ; and having checked the input using: if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "" . $conn->error; } i was kindly reminded that I had not set a default value for the ID in the database!
I am a beginner in php(& mysql).I am trying to insert form data into my database.But it does not work.Clicking on the 'Register' button on User_info.php page just displays a link to my home page.
Sign Up.php
<!DOCTYPE html>
<html>
<head>
<title>Details</title>
</head>
<body bgColor="Red">
<h1 style="color:blue">Please provide your details to become a registered user</h1>
<form style="color:blue" action="User_info.php" method="post">
User Id:     <input type="text" name="user_id" value="">
<br><br>
Password: <input type="password" name="password" value="">
<br><br>
Email Id:   <input type="text" name="email_id" value="">
<br><br>
Phone:      <input type="text" name="phone_no" value="">
<br><br>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
User_info.php
<!DOCTYPE html>
<html>
<head><title>User Information</title></head>
<body>
<?php
$hostname="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="movie store"; // Database name
$tbl_name="user"; // Table name
// Connect to server and select database.
$con=mysql_connect($hostname, $username, $password);
if(!$con)
{
die('Could not connect: '. mysql_error());
}
mysql_select_db($db_name,$con);
$id = $_POST['user_id'];
$pass = $_POST['password'];
$email = $_POST['email_id'];
$phone= $_POST['phone_no'];
$sql="INSERT INTO $tbl_name(user_id,password,email_id,phone_no) VALUES('$id','$pass','$email','$phone')";
if(!mysql_query($sql,$con))
{
die('Error: '. mysql_error());
}
print_r "1 record inserted";
// close connection
mysql_close($con);
?>
Return to Home
</body>
</html>
There is syntax error on line #29 of User_info.php
use echo "1 record inserted"; instead of print_r "1 record inserted";
MySQL extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. Ref
Please update your 'User_info.php' with following code as quick MySQLi solution.
<!DOCTYPE html>
<html>
<head><title>User Information</title></head>
<body>
<?php
$hostname="localhost"; // Host name
$username="root"; // mysqli username
$password=""; // mysqli password
$db_name="movie store"; // Database name
$tbl_name="user"; // Table name
// Connect to server and select database.
$con=mysqli_connect($hostname, $username, $password);
if(!$con)
{
die('Could not connect: '. mysqli_error());
}
mysqli_select_db($con, $db_name);
$id = $_POST['user_id'];
$pass = $_POST['password'];
$email = $_POST['email_id'];
$phone= $_POST['phone_no'];
$sql="INSERT INTO $tbl_name (user_id,password,email_id,phone_no) VALUES('$id','$pass','$email','$phone')";
if(!mysqli_query($con, $sql))
{
die('Error: '. mysqli_error($con));
}
echo "1 record inserted";
// close connection
mysqli_close($con);
?>
Return to Home
</body>
</html>