MySQL: no database selected error - php

hi i have an sql error says: no database selected this is my KK.php file:
$user_name = "root";
$password = "";
$database = "MyDB";
$server = "localhost";
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$message = mysqli_real_escape_string($link, $_POST['input1']);
$sql="INSERT INTO demo (message)
VALUES ('$message')";
if (!mysqli_query($link,$sql)) {
die('Error: ' . mysqli_error($link));
}
echo "1 record added";
mysqli_close($link);
?>
my database is "MyDB", and my demo.php file:
<form action="KK.php" method="post" />
<p>Message: <input type="text" name="input1" /></p>
<input type="submit" value="Submit" />
</form>
so what is the problem?, how do i select database?

Are you forgetting to call the mysqli_connect to get your connection?
ie:
$con = mysqli_connect("localhost","my_user","my_password","my_db");

Further to my comment above here is the code you are missing.
$user_name = "root";
$password = "";
$database = "MyDB";
$server = "localhost";
// This
$link = mysqli_connect($server,$user_name,$password,$database); // This
// This
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

You didn't call mysqli_connect
$con = mysqli_connect("localhost","my_user","my_password","my_db");

Related

I GET "No database selected" ERROR even that is selected

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>

MySQL db isn't populating

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.

Entering data into mysql database using php

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.

PHP SQL : How to save data to multiple database from one html form OR how to copy data from one database to another database automatically

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.

Problems with input form

I created a simple form through with I would like to update some info in mysql database. I through it all looks fine but i get some error
I got (two files):
<?php
$db_name = "test2";
$un = "jharvard";
$pw = "crimson";
$host = "localhost";
$connect = mysql_connect($host, $un, $pw);
mysql_select_db($db_name) or die(mysql_error());
echo ("succesfully conneted to the database!");
?>
and
<?php
if (isset($_POST['submitted']))
{
//Dit is de php file waarmee je connectie met de database maakt.
include ("addEmployee.php");
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sqlinsert = "INSERT INTO customers (name, address) VALUES ('$fname', '$lname')";
if (!mysqli_query($connect, $sqlinsert))
{
die ('error!');
}
}
?>
<html>
Add somebody!
<body>
<form method= "post" action="oefInsertData.php">
<input type = "hidden" name ="submitted" value="true" />
First name: <input type = "text" name="fname"/>
Last name: <input type = "text" name="lname"/>
<input type="submit" value="Add new person"/>
</form>
</body>
If i run it I get the following error: ! ) Warning: mysqli_query() expects parameter 1 to be mysqli, resource given in /home/jharvard/vhosts/pset7/public/oefInsertData.php on line 16
Anybody know what goes wrong here?
You are using both my_sql and my_sqli extension together..
Use this..
$connect = mysqli_connect($host, $un, $pw, $db_name);
and avoid
mysql_select_db($db_name) or die(mysql_error());
replace
<?php
$db_name = "test2";
$un = "jharvard";
$pw = "crimson";
$host = "localhost";
$connect = mysql_connect($host, $un, $pw);
mysql_select_db($db_name) or die(mysql_error());
echo ("succesfully conneted to the database!");
?>
with
<?php
$con=mysqli_connect("localhost","jharvard","crimson","test2");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
you have switch from mysql_ to mysqli_ so $connect is not a mysqli parameter change this by using mysqli_connect reference
<?php
$db_name = "test2";
$un = "jharvard";
$pw = "crimson";
$host = "localhost";
?>
and
<?php
if (isset($_POST['submitted']))
{
//Dit is de php file waarmee je connectie met de database maakt.
include ("addEmployee.php");
mysql_connect("$host", "$un", "$pw")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = mysql_query("INSERT INTO customers (name, address) VALUES ('{$fname}', '{$lname}')");
if(!$query){ echo mysql_error(); }
}
?>

Categories