I wanted to add New table in my database and this table should have 5 columns but it should be done by filling up a form in the website Let's say I'm going to add Travel Order table with it's five columns. Now i have this code in my form and it gives me this error: Call to undefined method mysqli::mysqli_real_escape_string()
<input type="text" class="form-control1" onKeyPress= "return lettersOnly(event)" name= "categoryname" id="categoryname" placeholder="Category Name..." maxlength="30" reqiured> this for the table name.
<input type="text" class="form-control1" onKeyPress= "return lettersOnly(event)" name="firstattrib" id="firstattrib" placeholder="..." maxlength="30"> this for one of the column. (please don't mind my naming of variables)
`
$connect = mysqli_connect("localhost","root","","doctrack_db");
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
// sql to create table
$sql = "CREATE TABLE ".$categoryname." (
id INT(6) UNSIGNED AUTO_INCREMENT NOT NULL,
file LONGBLOB(30) NOT NULL,
)";
$firstattrib = $connect->mysqli_real_escape_string($_POST['firstattrib']);
//query to add columns to table
$query = 'ALTER TABLE ' .$categoryname . '
ADD COLUMN '. $firstattrib .' VARCHAR(30) TINYINT NOT NULL DEFAULT \'0\' AFTER file';
if ($connect->query($sql)&$connect->query($query) === TRUE) {
echo "alert('Category created successfully!!')";
} else {
echo "alert('Error creating Category!!')" . $connect->error;
}
$connect->close();
?>`
Can you please tell me which part i got wrong or is it wrong as a whole?
try this
<?php
// Create connection
mysql_connect("localhost","root","","test") OR die("Server Connection error");
mysql_select_db("test") OR die("DB error");
$category = "category";
// sql to create table
$sql = "CREATE TABLE ".$category." (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if(mysql_query($sql)){
$sql1 = "INSERT INTO ".$category." (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
mysql_query($sql1);
}
?>
and it doesn't matter when you create table, what matter is when you inserting data into table have to has exist.
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 3 years ago.
I am about to create a table, but I want to declare it based on the user's input. thankyou for any response, all answers are appreciated, more power!
I am receiving this error (Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''2020-2021' ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR' at line 1)
here's the sample code I am doing.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mias";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$table = $_POST['usersinput'];
// sql to create table
$sql = "CREATE TABLE $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
Try this code by replacing your code. It will work. i have tried. Problem in your last line of your code.
CREATE TABLE $table(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30),
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
As Nigel has said in the comment, it's definitely a bad idea to allow user input to create a table.
How I would think about doing this would be to use relationships between the Table Guests and the Table or Booking you want them to be added to.
You would just need to create two tables, one for the Booking and one for the Guests then in the Guests table, have a Booking_ID field which would contain the ID of the bookings the user should be added to.
This way, when you want to look for Guests for a specific table, you would be able to do SELECT * FROM MyGuests WHERE booking_id=[the booking id] and this would return the guests for that table.
Like other users stated there are several reasons (most importantly security) not to do that, but if you really want it you have to use concatenation for your string:
Option
$sql = "CREATE TABLE {$table}(id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30), email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
Option
$sql = "CREATE TABLE" . $table . "(id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30), email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
I cannot access the textbox content to create the table in Mysql and the error is
"Error creating table: Incorrect table name ''
<?php
$conn=mysqli_connect("localhost","root","","abc");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = isset($_POST['email']) ? $_POST['email'] : '';
// sql to create table
$sql = "CREATE TABLE `$email` (
`id` INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`firstname` VARCHAR(30) NOT NULL,
`lastname` VARCHAR(30) NOT NULL,
`email` VARCHAR(50),
`regdate` TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
If error is "Error creating table: Incorrect table name" and you query has:
CREATE TABLE `$email`
Most probably $email has an # sign in it, that shouldn't be part of a table name - use only [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore).
It is not likely that a table should be created each form sublimation, and that its name should be dynamic (you will not know it to query data from this table).
Not less important - never use user input directly in your SQL (to avoid SQL injection). Reference:
PHP MySQLi Prepared Statements Tutorial to Prevent SQL Injection
You can try as follows-
$email = $_POST['email'];
// sql to create table
$sql = "CREATE TABLE IF NOT EXISTS $email(
`id` INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`firstname` VARCHAR(30) NOT NULL,
`lastname` VARCHAR(30) NOT NULL,
`email` VARCHAR(50),
`regdate` TIMESTAMP
)";
I get the "Table creation success" message but no table is created.
<html>
<body>
<?php
$con=mysql_connect("localhost","root","");
//create db
mysql_query("CREATE DATABASE VashDedomenwn2", $con);
echo "Db creation success <br>";
//create table
$sql= mysql_query("CREATE TABLE VashDedomenwn2.phone_book
(
personID int NOT NULL,
PRIMARY KEY(person ID),
LastName varchar(20) NOT NULL,
FirstName varchar(20),
Address varchar(30),
Age int,
Phone varchar(10)
)
");
mysql_query($sql,$con);
echo "Table creation success <br>";
//END CONNECTION
mysql_close($con);
?>
</body>
</html>
I'm a newbie in php! Probably it's a stupid mistake... Thanks fot the help
Before you create a table, you must open the database you created.
//create db
mysql_query("CREATE DATABASE VashDedomenwn2", $con);
echo "Db creation success <br>";
mysql_select_db("database name", $con);
//create table
...
And change
$sql= mysql_query("CREATE TABLE VashDedomenwn2.phone_book
(
...
)
");
to
$sql= mysql_query("CREATE TABLE `VashDedomenwn2.phone_book`
(
...
)
");
OK, as #php_purest said, use mysqli is better. Mysqli is the improved version of mysql which support OOPS. It can reduce the pressure of your server.
Like this:
$conn = new mysqli("localhost","root","");
$conn->query("CREATE DATABASE VashDedomenwn2");
echo "Db creation success <br>";
$conn->select_db("VashDedomenwn2");
//create table
$conn->query("CREATE TABLE `VashDedomenwn2.phone_book`
(
personID int NOT NULL PRIMARY KEY,
LastName varchar(20) NOT NULL,
FirstName varchar(20),
Address varchar(30),
Age int,
Phone varchar(10)
)
");
echo "Table creation success <br>";
//END CONNECTION
$conn->close();
This is what I have so far.... I do not understand why it is not working? Any ideas? This is just a simple script to connect to a database, create a table and insert some data. I also want to retrieve the data but I think I may be jumping a little a head.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
if (mysql_query("CREATE_DATABASE nogjhghkgst98", $link))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
if ($link="CREATE TABLE contactsZ8 (id int(6) NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15) NOT NULL,phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,email varchar(30) NOT NULL,web varchar(30) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))") {
echo "ineserted";
}
else
{
echo "not inserted" . mysql_error();
}
$link = "INSERT INTO contactsZ VALUES ('','John','Smith','01234 567890','00112 334455','01234 567891','johnsmith#gowansnet.com','http://www.gowansnet.com')";
$link="SELECT * FROM contactsZ";
$link=mysql_query($link);
mysql_close($link);
?>
There is definitely something wrong:
if ($link="CREATE TABLE contactsZ8 (id int(6) NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15) NOT NULL,phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,email varchar(30) NOT NULL,web varchar(30) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))") {
an assignment in an if
query not executed (that is not so bad: once the table is created, executing again the query when reloading the page will fail)
assigning to $link ! this is confusing (but should not generate any error)...
Then :
$link = "INSERT INTO contactsZ VALUES ('','John','Smith','01234 567890','00112 334455','01234 567891','johnsmith#gowansnet.com','http://www.gowansnet.com')";
The query is not executed.
Edit: the INSERT is done in contactsZ, whereas the CREATE TABLE creates contactsZ8.
Edit2: And finally:
mysql_close($link);
After re-assigning 3 times $link, $link is not the (optional, by the way) link identifier any more...
Is it true that after a user signs up, a sql table is create for him to store his posts ?
I make it similar in mysql after the man insert him into my page. The database is the same name with but the table name is made when he log in first time.
class Users
{
var $username="root";
var $password="pass";
var $database="InsertIntoStackOverflow";
var $table_name="";
public function Users($username)
{
$table_name=$username."_tb";
echo $table_name."<br/>";
mysql_connect(localhost,$username, $password) or die("unable to connect to database ".mysql_error());
echo $database."<br/>";
mysql_selectdb($database) or die("unable to select db ".mysql_error());
$query="CREATE TABLE ".$table_name." (id tinyint(4) NOT NULL AUTO_INCREMENT, title VARCHAR(128) NOT NULL, date_post VARCHAR(100), date_edit VARCHAR(100), post_content TEXT NOT NULL)";
mysql_query($query) or die("Unable to create table. ".mysql_error());
}
}
But it display only table_name and an error, the database name not display. Error is NO DATABASE IS SELECTED/
EDIT
This class is call after he sign up
I also have a function postApost but when I do
ob_start();
session_start();
require("Users_DB.php");
$name=$_SESSION['user'];
echo 'Welcome '.$name;
$username=new UserDB($name);
there is no table created
Two variables with same name $username. Use $this for accessing variable of class. Missing quote(") with localhost - it must be string type parameter. and this code can't create table on Database because you use AUTO_INCREMENT on your code but forgot to mention that as a PRIMARY KEY. I think the following code help you a lot.
class Users
{
var $username="root";
var $password="pass";
var $database="InsertIntoStackOverflow";
var $table_name="";
function __construct($user_name)
{
$this->table_name=$user_name."_tb";
echo $this->table_name."<br/>";
mysql_connect("localhost",$this->username, $this->password) or die("unable to connect to database ".mysql_error());
echo $this->database."<br/>";
mysql_selectdb($this->database) or die("unable to select db ".mysql_error());
$query="CREATE TABLE ".$this->table_name." (id tinyint(4) NOT NULL AUTO_INCREMENT, title VARCHAR(128) NOT NULL, date_post VARCHAR(100), date_edit VARCHAR(100), post_content TEXT NOT NULL, PRIMARY KEY (id))";
mysql_query($query) or die("Unable to create table. ".mysql_error());
}
}
And you can use this class by the following way :
$clsName = new Users('username');
Create one table:
CREATE TABLE Posts (
id TINYINT(4) NOT NULL AUTO_INCREMENT,
user VARCHAR(20) NOT NULL,
title VARCHAR(128) NOT NULL,
date_post DATETIME,
date_edit DATETIME,
post_content TEXT NOT NULL
)
Inserting new posts:
$insert = "
INSERT INTO Posts (
user,
title,
date_post,
date_edit,
post_content
) VALUES (
'$username',
'$title',
NOW(),
NOW(),
'$post_content'
)
";
Updating is simple:
$update = "
UPDATE Posts SET
title = '$title',
post_content = '$post_content',
date_edit = NOW()
WHERE id = '$postid';
";
Get all posts for user:
$posts = "
SELECT title, date_post, date_edit, post_content
FROM Posts
WHERE user = '$username'
ORDER BY date_post
";