Why is it not creating the table Simpsons? - php

This is the PHP code that acts as 'action' for another HTML page that has only a form in it.
It doesn't show any errors and after I click submit the message 'Database created' appears, but it's not creating the table 'Simpsons'. Why is this happening?
Please, let me know if I should put more details or comment the code.
<?php
$database = 'basedados';
$username = 'root';
$password = '';
$first = $_POST['first'];
$last = $_POST['last'];
$phone = $_POST['phone'];
$mobile = $_POST['mobile'];
$fax = $_POST['fax'];
$email = $_POST['email'];
$web = $_POST['web'];
$con = mysql_connect(localhost, $username, $password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE IF NOT EXISTS $database", $con)) {
echo "Database created";
} else {
echo "Error creating database: " . mysql_error();
}
mysql_select_db($database, $con);
$create_table = "CREATE TABLE Simpsons
(
first varchar(15),
last varchar(15),
phone varchar,
mobile varchar,
fax varchar,
email varchar,
web varchar,
)";
$insert_values = "INSERT INTO Simpsons VALUES ($first','$last','$phone','$mobile','$fax','$email','$web')";
if (table_exists(Simpsons, $database)) {
mysql_select_db($database) or die("Unable to select database");
mysql_query($insert_values, $con);
} else {
mysql_select_db($database) or die("Unable to select database");
mysql_query($create_table, $con);
mysql_query($insert_values, $con);
}
function table_exists($table, $db) {
$tables = mysql_list_tables($db);
while (list ($temp) = mysql_fetch_array($tables)) {
if ($temp == $table) {
return TRUE;
}
}
return FALSE;
}
mysql_close($con);
?>
Update:
Ok. Thank you all. Now my code looks more like this:
<?php
$database = 'basedados';
$username = 'root';
$password = '';
$first = $_POST['first'];
$last = $_POST['last'];
$phone = $_POST['phone'];
$mobile = $_POST['mobile'];
$fax = $_POST['fax'];
$email = $_POST['email'];
$web = $_POST['web'];
$con = mysql_connect(localhost, $username, $password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE IF NOT EXISTS $database", $con)) {
echo "Database created";
} else {
echo "Error creating database: " . mysql_error();
}
$create_table = "CREATE TABLE IF NOT EXISTS simpsons
(
first varchar(15),
last varchar(15),
phone varchar(15),
mobile varchar(15),
fax varchar(15),
email varchar(15),
web varchar(15)
)";
$insert_values = "INSERT INTO simpsons VALUES ('$first','$last','$phone','$mobile','$fax','$email','$web')";
mysql_select_db($database, $con) or die("Unable to select database: " . mysql_error());
mysql_query($create_table, $con) or die("Error creating table: " . mysql_error());
mysql_query($insert_values, $con) or die("Error inserting values: " . mysql_error());
mysql_close($con);
?>
I think it looks more clean, although I'm not sure I'm using the mysql_error() function correctly.
Thank you again.

One comma to much, and you need to specify the length of the varchar-fields
CREATE TABLE Simpsons
(
first varchar(15),
last varchar(15),
phone varchar(xx),
mobile varchar(xx),
fax varchar(xx),
email varchar(xx),
web varchar(xx)
)

There is a single quote missing in your table before $first:
INSERT INTO Simpsons VALUES ($first','$last','$phone','$mobile','$fax','$email','$web')
But to be honest, without a good error report it is hard to define which things are mistakes in your code and which are typos in your post.
BTW: Have a look at http://nl2.php.net/manual/en/function.mysql-escape-string.php

Why do you call mysql_select_db($database) when only a few lines before you called mysql_select_db($database, $con)? I would drop it.
Not an answer but a refactoring suggestion I couldn't fit into a comment:
if (table_exists(Simpsons, $database)) {
mysql_select_db($database) or die("Unable to select database");
mysql_query($insert_values, $con);
} else {
mysql_select_db($database) or die("Unable to select database");
mysql_query($create_table, $con);
mysql_query($insert_values, $con);
}
could just become
// connect statement dropped
if (!table_exists(Simpsons, $database)) {
mysql_query($create_table, $con);
}
mysql_query($insert_values, $con);
or even eliminated altogether by modifying your creation query's first line to read CREATE TABLE Simpsons IF NOT EXISTS and replacing the above lines with:
mysql_query($create_table, $con);
mysql_query($insert_values, $con);

maybe for first try to execute this code via cli or phpmyadmin if you don't know how to use mysql_error (see examples on page its really easy)

Related

mysql api submite towice

I tried many times to submit the form when it submitted it repeated the submission twice on the data. I don't understand why,please help me. and when I put the header location it doesn't work ever
here is the code
<?php
$name= $_POST['form_name'];
$mrn= $_POST['form_mrn'];
$mobile= $_POST['form_mobile'];
$link = mysql_connect('server', 'user', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('dbname');
if (!$db_selected) {
die('Could not select database: ' . mysql_error());
}
mysql_set_charset('utf8',$link);
$query = "INSERT INTO pharmacy ( name , mrn , mobile ) VALUES ('$name', '$mrn', '$mobile')";
$result = mysql_query($query);
header('Location: form.html');
$link->close();
?>
<?php
$name= $_POST['form_name'];
$mrn= $_POST['form_mrn'];
$mobile= $_POST['form_mobile'];
$link = mysql_connect('server', 'user', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('dbname');
if (!$db_selected) {
die('Could not select database: ' . mysql_error());
}
mysql_set_charset('utf8',$link);
//Just Put this code before inserting
if($name !=""){
$query = "INSERT INTO pharmacy ( name , mrn , mobile ) VALUES ('$name','$mrn', '$mobile')";
$result = mysql_query($query);
header('Location: form.html');
}
$link->close();
?>
Just check condition before insert. Let me know if facing same issue.

Basic PHP entry failing

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.

PHP Error: No database selected (Hostgator.com)

I have a problem with inserting data to MySQL with PHP.
When I run this code on my Hostgator hosting I get error like this:
No database selected
Here is my code:
$dbh= mysql_connect("localhost", $username, $password);
// or die ('I cannot connect to the database because: ' . mysql_error());
if(!$dbh)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("contafe_tipster", $dbh);
//$conn = mysqli_connect($servername, $username, $password, $dbname);
//Check connection
/*
if (!$conn) {
// Connection failed return 0
//die("Connection failed " . mysqli_connect_error());
echo "1";
}
*/
//Posted parameters
$pName = $_POST['name'];
$pCountry = $_POST['country'];
$pCity = $_POST['city'];
$pLocationX = $_POST['locationX'];
$pLocationY = $_POST['locationY'];
$pDescription = $_POST['description'];
$pMobileNumber = $_POST['mobile'];
$pOtherNumber = $_POST['phone'];
$pOpens = $_POST['opens'];
$pCloses = $_POST['closes'];
$add_DB = "INSERT INTO Places (Id, Name, Country, City, LocationX, LocationY, Description, Mobile, Phone, Opens, Closes)
VALUES(NULL, '$pName', '$pCountry', '$pCity', '$pLocationX', '$pLocationY', '$pDescription', '$pMobileNumber', '$pOtherNumber', '$pOpens', '$pCloses')";
if (mysql_query($add_DB, $dbh)) {
//if success return 1
echo "0";
}
else {
//if error return -1
//echo "2";
die('Error: ' . mysql_error());
}
mysql_close($dbh);
Are you sure that db name is correct?
Try this way of connection with db:
mysql_connect ($dbhost,$dblogin,$dbpass) or die ("Can't connect to database");
mysql_select_db($db) or die ('Wrong databse!');

Updating MySQL Error but nothing is wrong in code?

So I get this error:
Problem updating record. MySQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE KittenID = '2''
But then in my code:
<?php
if(isset($_POST['Modify']))
{
$connection = mysql_connect("Deleted the login info");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{
//select a database
$dbName="Katz";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{
$KittenID = $_POST["KittenID"];
$KittenAge = $_POST['KittenAge'];
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Gender = $_POST['Gender'];
$Personality = $_POST['Personality'];
$Activity = $_POST['Activity'];
$Comments = $_POST['Comments'];
$query = "UPDATE Kittenzz
SET KittenID = '$KittenID',
KittenAge = '$KittenAge',
Name = '$Name',
Email = '$Email',
Gender = '$Gender',
Personality = '$Personality',
Activity = '$Activity',
Comments = '$Comments',
WHERE KittenID = '$KittenID'";
$res = mysql_query($query);
if ($res)
{
echo "<p>Record Updated<p>";
}
else
{
echo "Problem updating record. MySQL Error: " . mysql_error();
}
}
}
mysql_close($connection);
}
?>
It makes no sense, I've read those lines of code for an hour, I cannot see the problem. It should run. Can anyone lend me fresh eyes?
Remove the comma near '$comments'
$query = "UPDATE Kittenzz
SET KittenID = '$KittenID',
KittenAge = '$KittenAge',
Name = '$Name',
Email = '$Email',
Gender = '$Gender',
Personality = '$Personality',
Activity = '$Activity',
Comments = '$Comments'
WHERE KittenID = '$KittenID'";
it may possible that in connection username and password in required.
like this :-
$connection = mysql_connect("localhost","username","password");

INSERT statement not working mysql

When I process this data, the data is not being inserted into my database. This is my current database structure:
https://drive.google.com/file/d/0BzJ9StkJe55WaG1oaVhqcUJmSGc/edit?usp=sharing
I have no clue why it is not inserting. I am not getting an error message and I am seeing the successfully inserted data piece.
<head><title>Process Punch</title></head>
<?php
define('DB_NAME', 'name');
define('DB_USER', 'user');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'host');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link){
die('Could not connect: ' .mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}else{
$userid_value = $_POST['userid'];
$punchtype_value = $_POST['punchtype'];
$group_value = $_POST['group'];
$dept_value = $_POST['dept'];
$notes_value = $_POST['notes'];
$table = "tc_".$userid_value;
$date_value = date("Y-m-d h:i:s");
echo $table;
$sql = "INSERT INTO $table (punchtype, groupname, dept, notes) VALUES ('$punchtype_value', '$group_value', '$dept_value', '$notes_value')";
echo "Successfully inserted data";
}
?>
Execute the query with mysql_query(), concatenate the query
$sql = "INSERT INTO `".$table."` (`punchtype`, `groupname`, `dept`, `notes`) VALUES ('".$punchtype_value."', '".$group_value."', '".$dept_value."', '".$notes_value."')";
$qry = mysql_query($sql ,$link);
echo "Successfully inserted data";

Categories