I'm setting up a wedding invitation RSVP form. I have here what should be a basic PHP and SQL data entry, but I keep getting the error:
"Could not enter data: No database selected"
UPDATE - Many thanks to all your suggestions. I have updated my code as you can see bellow. I now get a new error as follows:
"Could not connect:" (witch is a message I output myself in line 7, but it does not show the error that should follow")
Does anyone know what this means please?
Here is my [UPDATED] code:
<?php
function submit(){
$con = mysqli_connect("localhost", "jaredand_rsvp", "jar3dandcr1st1na", "jaredand_rsvp");
if (!$con)
{
die('Could not connect: ' . $con->error);
}
$name = $_POST['name'];
$partnerName = $_POST['partner_name'];
$allergies = $_POST['allergies'];
$comments = $_POST['comment'];
$going = $_POST['going'];
$sql = 'INSERT INTO rsvp '.
'(name,partner_name, allergies, comments, going) '.
'VALUES ( "'.$name.'", "'.$partnerName.'", "'.$allergies.'", "'.$comments.'", "'.$going.'")';
$result = $con->query($sql);
if(!$result )
{
die('Could not enter data: ' . $result->error);
}
echo "Entered data successfully\n";
mysqli_close($con);
}
if(isset($_POST['name']))
{
submit();
}
?>
Can anyone please advise me on what I am doing incorrectly?
That happens because mysql_connect doesn't have database name as parameter.
You should connect to the server, and then select a database by calling mysql_select_db
Cheers!
this is the right way
$con = mysql_connect("localhost","USERNAME","PASSWORD);
mysql_select_db('jaredand_rsvp', $con);
but please use "mysqli"
$con = mysqli_connect("localhost", "USERNAME", "PASSWORD, "jaredand_rsvp");
$result = $con->query($sql);
happy to help,
for security is better if you escape your values before insert :
$name = $con->real_escape_string($_POST['name']);
$partnerName = $con->real_escape_string($_POST['partner_name']);
$allergies = $con->real_escape_string($_POST['allergies']);
$comments = $con->real_escape_string($_POST['comment']);
$going = $con->real_escape_string($_POST['going']);
Try to connect to the database first and then select the database name
I hope this will fix your issue
Or you could use PDO because mysql_connect is depricated
You have used $con = mysql_connect(); at the top and bottom you are using:
mysqli_close();
First follow the same standarad. Use mysqli instead of sqli at top.i.e,
$con = mysqli_connect("localhost","USERNAME","PASSWORD", "jaredand_rsvp");
Remove the line: mysql_select_db('jaredand_rsvp');
and replace $retval = mysql_query( $sql, $con ); with
$retval = mysqli_query( $sql, $con );
Use it another Way
<?php
function submit() {
$host = "localhost";
$username = "root";
$password = "";
$dbname = "jaredand_rsvp";
$con = new mysqli($host, $username, $password, $dbname);
if ($conn -> connect_error) {
die("Connection failed: " . $conn -> connect_error);
}
$name = $_POST['name'];
$partnerName = $_POST['partner_name'];
$allergies = $_POST['allergies'];
$comments = $_POST['comment'];
$going = $_POST['going'];
$sql = 'INSERT INTO rsvp ' . '(name,partner_name, allergies, comments, going) ' . 'VALUES ( "' . $name . '", "' . $partnerName . '", "' . $allergies . '", "' . $comments . '", "' . $going . '")';
if($con->query($sql)== TRUE){
echo "Data Inserted";
}
else {
echo mysqli_error($con);
}
mysqli_close($con);
}
if (isset($_POST['name'])) {
submit();
}
?>
How about using MySQLi instead of the now depreciated MySQL?
EDIT
Okay, I see no connection being made to the database. Something like
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
If you have stored the db connect credential on a different file then i see no include or require mentioned on your this script either. Check if you have made the connection and then get back.
Related
I want to set up a website with a form in it. The form will transfer the data to the DB, but I think it is not safe to let the personal data in the DB which is external reachable.
So I thought I should transfer the data via PHP from the DB1(server1 - external reachable) to DB2(server2 - only internal reachable).
The following picture should help to know what I am searching for.
Is there any names/methods to google for?
From php you just have to create a new connection for DB2.
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
$servername2 = "localhost";
$username2 = "database2";
$password2 = "xxxxxxxx";
$dbname2 = "database2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn2 = new mysqli($servername2, $username2, $password2, $dbname2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->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 ($conn2->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn2->error;
}
$conn->close();
$conn2->close();
?>
New to php and am connecting form attributes to php to connect to a godaddy mysql. Every attempt ends in a blank screen with no error messages. Is there any syntax errors the jump out? My sublime text wont register php syntax, but thats another problem for another time. I may need to call up godaddy support? the password has been removed for privacy.
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysql_select_db('EOTDSurvey', $con)
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
$_POST['BI1']
$_POST['BI2']
$_POST['BI3']
$_POST['BI4']
$_POST['BI5']
$_POST['BI6']
$_POST['BI7']
$_POST['BI8']
$_POST['BI9']
$_POST['BI10']
$_POST['BI11']
$_POST['BI12']
$_POST['BI13']
$_POST['BI14']
$_POST['BI15']
$sql = "INSERT INTO Survey1(BI1)"
$sql = "INSERT INTO Survey1(BI2)"
$sql = "INSERT INTO Survey1(BI3)"
$sql = "INSERT INTO Survey1(BI4)"
$sql = "INSERT INTO Survey1(BI5)"
$sql = "INSERT INTO Survey1(BI6)"
$sql = "INSERT INTO Survey1(BI7)"
$sql = "INSERT INTO Survey1(BI8)"
$sql = "INSERT INTO Survey1(BI9)"
$sql = "INSERT INTO Survey1(BI10)"
$sql = "INSERT INTO Survey1(BI11)"
$sql = "INSERT INTO Survey1(BI12)"
$sql = "INSERT INTO Survey1(BI13)"
$sql = "INSERT INTO Survey1(BI14)"
$sql = "INSERT INTO Survey1(BI15)"
if ($conn->query<$sql) === TRUE) {
echo "IT FUCKING WORKS.";
}
else{
echo "didnt workkkkkk";
}
$conn->close();
?>
please connect database like this...
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
And Use mysqli_select_db instead of mysql_select_db
And insert semi-colon (;) after every line end according to php code standard.
There are a lot of issues with this code, as mentioned the mysqli_select_db issue. The $_POST['BIx'] will also cause errors because there is no semi-colon after each statement. You're missing a '(' on the line if ($conn->query<$sql) === TRUE) { not to mention that line will not work anyway because you're logically comparing a resource type (I think) to a string.
You're also never executing the insert statements. All around I seriously think you should practice PHP coding some more and read up on how to use mysqli properly: see here.
Regards
EDIT: You also have a closing PHP tag at the end of your script which is generally not a good idea as explained here
EDIT 2: Also using an IDE such as Netbeans is always a good idea as it can highlight syntax errors instead of asking SO to do it for you ;)
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysqli_select_db('EOTDSurvey', $con);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
############# Function For Insert ##############
function insert($tableName='',$data=array())
{
$query = "INSERT INTO `$tableName` SET";
$subQuery = '';
foreach ($data as $columnName => $colValue) {
$subQuery .= " `$columnName`='$colValue',";
}
$subQuery = rtrim($subQuery,', ');
$query .= $subQuery;
pr($query);
mysqli_query($con,$query) or die(mysqli_error());
return mysqli_insert_id();
}//end insert
#########################################
if(isset($_POST['submit'])){
unset($_POST['submit']);
//print_r($_POST);
$result=insert('Survey1',$_POST);
if($result){
echo '<script>window.alert("Success!");</script>';
echo "<script>window.location.href = 'yourpage.php'</script>";
}
}
$conn->close();
?>
include_once 'dbfunction.php';
getDbConnect();
mysqli_query("DELETE FROM crewlist WHERE id = $_GET[crew_id]") or die (mysqli_error());
echo 'Delete success';
header ('Location: crewlisting.php');
This code doesn't work, however when I replace the crew_id with the actual primary key via hard coding the delete function works
Use this (MySQLi Procedural)
In dbfunction.php should be
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
?>
and insert page should be
<?
include ("dbfunction.php"); //include db connection
$id = $_REQUEST['crew_id'];
$sql = "DELETE FROM crewlist WHERE id = '$id' ";
if (mysqli_query($conn, $sql))
{
echo "Record deleted successfully";
}
else
{
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Errors are
There is no function define in getDbConnect()
If you are confusing with 'and " then split the functions
$id = $_REQUEST['crew_id'];
$sql = "DELETE FROM crewlist WHERE id = '$id' ";
Use mysqli_query and mysqli_error in correct format
and error in mysqli_query, You are not passing connection to MySQLi
When ever database part is Finished, Close connection mysqli_close($conn);
Correct your query:
mysqli_query("DELETE FROM crewlist WHERE id ='".$_GET['crew_id']."'") or die('Error: ' . mysqli_error());
I'm not exactly sure what happened but this database and the php effecting it were working just fine until it hit the fourth row and now it won't insert new records at all.
if($_POST)
{
$servername = ******;
$username = ******;
$password = ******;
$db = ******;
$conn = mysqli_connect($servername, $username, $password, $db);
mysqli_select_db($conn,$db);
$uuid = $_POST['uuid'];
$sql = "INSERT INTO uuid VALUES ('$uuid');";
mysqli_query($conn,$sql);
mysqli_close($conn);
}
I'm not sure what happened but this is the relevant code for the mysqli query.
try this
<?php
if(isset($_POST['uuid']))
{
$servername = yourServerName;
$username = username;
$password = password;
$dbname = databaseName;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$uuid = $_POST['uuid'];
$sql = "INSERT INTO tableName (columnName) VALUES ('$uuid')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
Also, I recommend using prepared statements.
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.