Customer will complete a form and enter a pathway where they will want the CSV to be exported to. The pathway is entered using the top section of the php (below):
<form action="register.php" method="post">
Enter file pathway where CSV will be saved: <input type="text" name="username" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
</body>
I want to create a variable called pathway. At the moment I can get text entered into the correct row in the mysql database (I can get John printed in the database), but not the correct text that was entered into the form (i.e. $pathway).
I want to create a variable because after saving the pathway in the database i also want to use it in an export.php.
I am assuming i also need something like this:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$pathway = mysql_real_escape_string($_POST['pathway']);
// but i can't seem to piece it altogether.
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$table_users = $row['pathway'];
$pathway = "pathway";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('John')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
This shoud work, if not then check your usename and password...
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$pathway = $_POST['username']; username - is the name of your input.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('$pathway')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
your DB username is Null
Change $username = ""; to $username = "root";
Your input field name is username
change it to pathway for $_POST['pathway'] to work
<form action="register.php" method="post">
Enter file pathway where CSV will be saved:
<input type="text" name="pathway" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
First of all, you've got 'username' as the name of the field using for type a pathway, so rename it to 'pathway'.
I don't know if I understand you, but do you just want to read posted content?
Try something like:
$pathway = $_POST['pathway']
I strongly recommend to use object-oriented style with
$conn = new mysqli...
and then
mysqli->prepare(), mysqli->bind_param(), mysqli->execute()
With this you won't have to deal with mysqli_real_escape_string etc.
Related
i want to store a data to the mysql database but if i press the submit button it display the php page.
form:
<div id="test">
<form action="demo.php" method="post">
please enter the number(1 to 100) : <input type="text" name="value">
<input type="submit">
</form>
</div>
demo.php
<?php
$value=$_POST['value'];
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
if ($conn->query($input) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Replace $input with $sql in the if statement:
From
if ($conn->query($input) == TRUE) {
To
if ($conn->query($sql) == TRUE) {
Note: Since you are storing $_POST['value'] in $value, you don't need to use $_POST['value'] in the query, instead make use of $value.
There is one correction:
Change
if ($conn->query($input) == TRUE) {
To:
if ($conn->query($sql) == TRUE) {
Along with that, following are suggestions:
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
This query is OK, is value of $_POST['value'] is integer, but, for strings, it will create SQL Syntax Error.
Please correct this to:
$sql = "INSERT INTO input VALUES ('".$_POST['value']."')";
Observe, enclosed semi colon.
2) You are inserting only one field value and not specifying fields. This means you table has only field. Normally we do not have tables with only one field.
Please specify field names:
$sql = "INSERT INTO input (field_one) VALUES (".$_POST['value'].")";
Get values like this
$value=$_REQUEST['value'];
change the query to
$sql = "INSERT INTO input VALUES ('$value')";
1st : Add name attribute to submit button name="submit"
<input name="submit" type="submit">
2nd : use isset like this if(isset($_POST['submit'])){ //rest of code here }
3rd : Try to use prepared statement or pdo to avoid sql injection
demo.php
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$stmt = $conn->prepare("INSERT INTO input(value) VALUES (?)");
$stmt->bind_param('s',$_POST['value']);
//The argument may be one of four types:
//i - integer
//d - double
//s - string
//b - BLOB
//change it by respectively
if ($stmt->execute() == TRUE && $stmt->affected_rows>0) {
echo "New record created successfully";
} else {
echo "Error: <br>" . $conn->error;
}
}
$conn->close();
?>
Im new in MySql and PHP and im trying to make a CRUD but everytime i try to insert data into table called "studenti" i get the error that i didnt select a database but i selected a database with mysqli_select_db($con, "d_base");
Somebody please help me cuz i dont understand why its not workin'
Here is the code;
$id = $_POST['ID'];
$nota = $_POST['Nota'];
$emri = $_POST['Emri'];
$mbiemri = $_POST['Mbiemri'];
$servername = "localhost";
$dbname = "d_base";
// 1.Create connection
$con = mysqli_connect("localhost","d_base");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!mysqli_query($con,"INSERT INTO studenti (id, nota, emri, mbiemri) VALUES ('$id', '$nota','$emri','$mbiemri')"))
{
echo("Error description: " . mysqli_error($con));
}
// Perform queries
mysqli_select_db($con, "d_base");
mysqli_query($con,"INSERT INTO studenti (id, nota, emri, mbiemri) VALUES ('$id', '$nota','$emri','$mbiemri')");
mysqli_close($con);
Before all that if you are a begginer go straight on PDO or use mysqli with prepared statements its safer.
Here is example how your php and html form must look like and work.
First you must check if submit button is pressed, if its pressed read values form form $_POST variables.
Second thing you must escape injection to your mysql by using function mysqli_real_escape_string().
After that try to insert query and check for error, if there is no error query will be inserted successfully.
PHP code
<?php
// set error report ; 1 = on | 0 = off
error_reporting(1);
$db_host = "localhost"; // host
$db_user = "root"; // database username
$db_pass = ""; // database password
$db_name = "d_base"; // database name
// 1.Create connection
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// if form is submited
if (isset($_POST['submit']))
{
// escape post variables
$id = mysqli_real_escape_string($con, $_POST['ID']);
$nota = mysqli_real_escape_string($con, $_POST['Nota']);
$emri = mysqli_real_escape_string($con, $_POST['Emri']);
$mbiemri = mysqli_real_escape_string($con, $_POST['Mbiemri']);
// make query
$query = mysqli_query($con, "INSERT INTO studenti (id, nota, emri, mbiemri VALUES ('$id', '$nota', '$emri', '$mbiemri')")
// check for query
if (!$query)
{
echo "Error description: " . mysqli_error($con);
}
else
{
echo "Query inserted.";
}
// close connenction
mysqli_close($con);
}
?>
<form action="" method="post">
<input type="text" name="ID" placeholder="Id"><br />
<input type="text" name="Nota" placeholder="Nota"><br />
<input type="text" name="Emri" placeholder="Emri"><br />
<input type="text" name="Mbiemri" placeholder="Mbiemri"><br />
<input type="submit" name="submit" value="Submit form">
</form>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Php form for MySQL</title>
</head>
<body>
<form action="home.php" method="post">
<p>
<label for="table">Name your Table</label>
<input type="text" name="table" id="table">
</p>
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<button name="submit" type="submit" value="submit">Create Table</button>
</form>
if (isset($_POST['submit'])){
//enter database details
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$table = $_POST['table'];
// Create a MySQL table in the selected database
mysqli_query("CREATE TABLE $table (
firstname VARCHAR(30),
lastname VARCHAR(30),
email VARCHAR(50))") or die(mysql_error());
if ($conn->query($sql) === TRUE) {
echo "Table account created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
if(isset($_POST['firstname']) || ($_POST['lastname']) || ($_POST['email']))
{
$order="INSERT INTO $table (firstname,lastname,email) VALUES ('$firstname','$lastname','$email')";
$result = mysqli_query($order) or die (mysql_error());
}
mysqli_close($conn);
}
?>
</body>
</html>
I'm trying to allow the user to pick a name for the database and was stuck. I get an error
Access denied for user ''#'localhost' (using password: NO)
Picture of what I want:
I don't know what to do. Hope you can help. Thanks
The error you're getting means you're not providing valid credentials to connect to the database. Don't update them in your question, because these details should be private, but you need to change the code:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
to be the actual values. For instance, if your mysql username is 'tomi', the username line would look like this:
$username = "tomi";
You don't really have a database named 'database' do you? And if your actual password is 'password' you need to change it to something more secure.
You open a mysqli connection, and then use mysql_query to make a query, when it should be mysqli_query. mysql_* and mysqli_* are very different things, and you should never use mysql_* anymore. After changing this, check your authentication details. As long as you're on a private machine, maybe use var_dump() to look at them and make sure they're what you expect them to be. It looks like they might be getting passed into mysqli as empty strings. If your auth details are absolutely correct, double check that the given user in the database actually has the required privileges.
Editing my top answer with the full php code that I think will work for you:
<?php
if (isset($_POST['submit'])){
//enter database details
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "Failed to connect: (" . $conn->connect_error . ") ";
}
$table = $_POST['table'];
// SQL to Create a table in the selected database
$sql = "CREATE TABLE $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30),
lastname VARCHAR(30),
email VARCHAR(50))";
if ($conn->query($sql) === TRUE) {
echo "Table account created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Check connection
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
if(isset($_POST['firstname']) || isset($_POST['lastname']) || isset($_POST['email'])) {
$order="INSERT INTO $table (firstname,lastname,email) VALUES ('$firstname','$lastname','$email')";
if ($conn->query($order) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $order . "<br>" . $conn->error;
}
}
$conn->close();
}
?>
IMPORTANT:
1)
Make sure you enter the correct database details at the top of the php code. For example for me with xampp on windows it is:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
where I have previously created the database "database" manualy.
2) If you want to make sure in your later part of the code that all fields are NOT empty, you might prefer to use && (and) instead of || (or) for your conditions in the if. Currently it will run even as long as ANY of the fields are filled in, even if the rest of the fields are EMPTY.
Example:
if(isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email'])) {
instead of:
if(isset($_POST['firstname']) || isset($_POST['lastname']) || isset($_POST['email'])) {
I also highly suggest you check out the different ways to implement MySQLi with php; for example
Creating tables: http://www.w3schools.com/php/php_mysql_create_table.asp
I have a html form, say example
<form action="form.php" method="post">
First name:<br>
<input type="text" id="fname" name="fname">
<br>
Last name:<br>
<input type="text" id="lname" name="lname">
<br><br>
<input type="submit" value="Submit">
</form>
and form.php
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The form.php is saving that data to database1 .
I want that data to be saved to another database database2 along with database1.
Is it possible ?? If yes then what changes should be made in the code ?
If it is not possible then is it possible to copy data from database1 to database2 automatically? Whenever a new row is added in database1 then it should automatically copied to database2.
I want the same data to be in two different database. How can I achieve any of the above said ??
From php you just have to create new connection to DB.
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
$servernameS = "localhost";
$usernameS = "database2";
$passwordS = "xxxxxxxx";
$dbnameS = "database2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$connS = new mysqli($servernameS, $usernameS, $passwordS, $dbnameS);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($connS->connect_error) {
die("Connection failed: " . $connS->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
if ($connS->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $connS->error;
}
$conn->close();
$connS->close();
?>
What it sounds like you need is to setup replication.
Here is the official documentation on replication. Here is a simpler step-by-step guide setting it up.
If replication isn't what you wanted, you could accomplish the same thing by connecting to database2 in addition to database1 then running the query once on both.
You can use something like using mysqli::selectDB method:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to world db */
$mysqli->select_db("world");
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$mysqli->close();
?>
Check out the manual.
Similar question as yours at SO.
The problem: insert.php connects fine, but only inserts empty values ('') when I hit 'save' on the html form. The text I type, which I'm trying to insert, isn't saved. Somewhere a connection isn't being made and that data is lost but I can't figure out exactly where. Any help?
HTML insert form (collecting data for 2 parameters, 'user' and 'thread')
<form action="insert.php" method="post">
user: <input type="text" name="user"><br>
thread: <input type="text" name="thread"><br>
<input type="submit" value="Save">
</form>
PHP code to connect to SQL, insert inputted values
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "##.##.###";
$username = "harwoodjp";
$password = "~";
$dbname = "332";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (☒)<br/> " . $conn->connect_error);
}
echo "SQL (☑) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_connect($servername,$username,$password);
mysql_select_db("332project");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
try this
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
//create connection
$conn = mysql($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (☒)<br/> " . $conn->connect_error);
}
echo "SQL (☑) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_select_db("db");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
It might be because the default form posting method is GET.
Either change your $_POST to $_GET or add method="POST" to your form tag.