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>
Related
I have a formText.php file that contains a form with the following code form code:
<form action="insert.php" method="post">
<p>
<label for="theNames">Name:</label>
<input type="text" name="theName" id="theName">
</p>
<p>
<label for="theCitys">City:</label>
<input type="text" name="theCity" id="theCity">
</p>
<p>
<label for="theAges">Are you over eighteen?(Y/N)</label>
<input type="text" name="theAge" id="theAge">
</p>
<p>
<label for="theDates">Date:</label>
<input type="text" name="theDate" id="theDate">
</p>
<input type="submit" value="Submit">
</form>
Then I have an insert.php file with the following script:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root","phpteste");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security (EDITED)
$theName = mysqli_real_escape_string($link, $_POST['theName']);
$theCity = mysqli_real_escape_string($link, $_POST['theCity']);
$theAge = mysqli_real_escape_string($link, $_POST['theAge']);
$theDate = mysqli_real_escape_string($link, date("Y-m-d h:i:s",$_POST['theDate']));
// attempt insert query execution
$sql = "INSERT INTO tabelateste (id, name, city, overeighteen, date) VALUES (NULL, '$theName', '$theCity', '$theAge', '$theDate')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
My database is called phpteste and my table name is tabelateste.
What am I doing wrong here?
Whenever I click Submit nothing comes up and nothing gets added to the database.
Your post data name fields are wrong. SO you need to change below line:
// Escape user inputs for security
$theName = mysqli_real_escape_string($link, $_POST['theName']);
$theCity = mysqli_real_escape_string($link, $_POST['theCity']);
$theAge = mysqli_real_escape_string($link, $_POST['theAge']);
$theDate = mysqli_real_escape_string($link, date("Y-m-d h:i:s",$_POST['theDate']));
You need to change date to signup_date as per your database table structure.
$sql = "INSERT INTO tabelateste (name, city, overeighteen, signup_date) VALUES ('$theName', '$theCity', '$theAge', '$theDate')";
$sql = "INSERT INTO tabelateste (`name`, `city`, `overeighteen`, `date`) VALUES ('$theName', '$theCity', '$theAge', '$theDate')";
Use this code
I just tested your code (copied and pasted) and it works perfectly under my server configuration (Windows 10 - PHP 5.6) . My best guess is that you have a typo in either the table name or the MySQL configuration.
If you copied this code from another site. Please check that you created the database and the table , and that the MySQL configuration is correct.
A good to check for this kind of mistakes so is to read the PHP error logs
Try it like this maybe
if(isset($_POST['submit']) && !empty($_POST) ){
$theName = $_POST['theName'];
$theCity = $_POST['theCity'];
$theAge = $_POST['theAge'];
$theDate = $_POST['theDate'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "phpteste";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tabelateste (name, city, overeighteen, date)
VALUES ('$theName ', '$theCity ', '$theAge ', '$theDate ')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
I am trying to create a register/login html/php script. I created a database and I believe my html/php code is correct. I was wondering if I am missing something small. Here is my code so far.
Here is the database
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
if(isset($_POST["submit"]))
{
$User = "**";
$Password = "**";
$Database = "member";
$Host = "localhost";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
<form method="post" action="proInput.php">
Username:<input type="Text" name="username"><br>
Password:<input type="Text" name="password"><br>
<input type="Submit" name="submit" value="Register"></form>
<?
}
?>
Every time I type SELECT * FROM member; in MySQL my database is empty.
mysqli_commit($con);
mysqli_query($con,$sql);
mysqli_close($con);
You're committing before you insert, and then closing an uncommitted transaction. Try swapping the first two lines in the above excerpt.
As you answered already in your comment,
the name of the file isn't main_login.php but proinput.php
Your form is posting it's data to main_login.php and I'm assuming you don't have the insert query on that page, your code isn't run at all.
Options:
Try changing the name of this php file to main_login.php and then instead of the echo redirect the user to the login page
Move this part of the insert to your main_login.php
if(isset($_POST["submit"]))
{
$User = "";
$Password = "";
$Database = "member";
$Host = "localhost";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
for debugging add the following to the very top of your php file right after the opening of php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
This worked for me
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
if(isset($_POST["submit"]))
{
$User = "db_user";
$Password = "db_password";
$Database = "db_name";
$Host = "db_host";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
<form method="post" action="proinput.php">
Username:<input type="Text" name="username"><br>
Password:<input type="Text" name="password"><br>
<input type="Submit" name="submit" value="Register"></form>
<?php
}
?>
please add 'or die (mysqli_error())' at the end of your query and get the sql error report. That should tell you what is exactly wrong with sql . Php error reporting will only give php errors.
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.
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.
Can you scan my code below and work out why the form doesn't successfully insert a record in to my MySql table 'users'?
insert.php:
<?php // insert.php
require_once 'login.php';
$con = mysqli_connect($db_hostname, $db_username, $db_password, $db_database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_connect_error();
}
$sql = "INSERT INTO users (name, email)
VALUES
('$_POST[name]]','$_POST[email]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con;)
?>
index.html:
<html>
<body>
<h1>Hello!</h1>
<form action="insert.php" method="post">
Name: <input type="text" name="name">
Email <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
Login credentials stored in a separate login.php file.
Thanks!
You have an extra square bracket here
('$_POST[name]]',
^------- //Remove this from your SQL Query
You need to switch to PreparedStatements seriously as the above code of yours is directly prone to SQL Injection.
Try to do:
VALUES ('".$_POST[name]."','".$_POST[email]."')";
so... use mysqli_real_escape_string for sql injection as it:
example:
$name = mysqli_real_escape_string($_POST['name']);
and it is mysqli_close($con); not mysqli_close($con;)
For one thing, this line mysqli_close($con;) has a misplaced semi-colon, which should read as mysqli_close($con);
Typo or not, it was posted that way, but I'm not betting my bottom dollar on it.
Plus, your present method is open to SQL injection.
There was a slight syntax error in $_POST[name]] which should have read as $_POST[name] however, as Patrick Evans stated in a comment:
"While that is a typo it wouldn't cause the sql to fail, it would just add a ] to the end of the name in the column."
Use this method instead: (PDO) - it's safer.
<?php
/* Your Database Credentials */
$dbname = 'your_database';
$username = 'username';
$password = 'password';
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (name,
email
) VALUES (
:name,
:email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->execute(array(':name' => $_POST['name'],':email' => $_POST['email']));
if($stmt != false) {
echo "Success!";
} else {
echo "An error occured saving your data!";
}
?>
And your existing, with a few modifications:
<?php // insert.php
require_once 'login.php';
$con = mysqli_connect($db_hostname, $db_username, $db_password, $db_database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_connect_error();
}
$name=mysqli_real_escape_string($con,$_POST['name']);
$email=mysqli_real_escape_string($con,$_POST['email']);
$sql = "INSERT INTO users (name, email)
VALUES
('$name','$email')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>