Am a newbie in PHP and MySQL, how can I create a database with a phone number being the database name? The phone number is in the format of +256720742675. I have tried the code below but keeps on trowing an error.
<?php
$database= $_POST[PhoneNumberTextBox];
//check for MySQL server connection
$connection = mysql_connect("localhost","root","");
if (!$connection)
{
die('Could not connect to database: ' . mysql_error());
}
//Create database
$sql= "CREATE DATABASE $database";
if(!mysql_query($sql,$connection))
{
die('Could not create database'.mysql_error());
}
else
echo"Database Created<br\>";
//Close connection
mysql_close($connection);
?>
don't know where to begin... From:
You should not use root database user in your php file or,
You should not create databases from your _POST requests
I can see so many bad things happening...
First of all it doesnt sound right to create a table for each number.
Starting a database name with a number is not allowed. If you insist though, try prepending a letter to it.
For Example: N256720742675
The answer is to store telephone numbers in a field. Not create a new database per telephone number:
Create a table like this:
create table phonenumbers (
phone varchar(20) not null primary key,
related_field1
......
related_field25
Now you can use code like this:
$conn = mysql_connect("localhost","named_user","long_password_with_entropy");
$phone = mysql_real_escape_string($_POST['PhoneNumberTextBox']);
$sql = "INSERT INTO phonenumbers (phone, field1, field2, field3)
VALUES ('$phone','1','2','3') ";
//The quotes ^ ^ are essential !
Now you're storing stuff in a database in a way that enables them to be retrieved.
And you can select all your data per phonenumber like this:
SELECT p.*, c.*
FROM phonenumbers p
LEFT JOIN calls c ON (c.phonenumber = p.phone)
WHERE p.phone = '$phone';
Hard rules
Set a strong password on your user account.
Don't log in with root.
Escape all $_* super globals using mysql_real_escape_string. (Or even better: use PDO).
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
See this tutorial about mysql and php: http://www.tizag.com/mysqlTutorial/
It's one of the few that get this topic right.
Related
This question has kinda been asked already but I couldn't find my answer. I searched a while and found these related questions, but they didn't help me to understand or answer my problem.
SQL Insert Into with Inner Join
T-SQL INSERT INTO with LEFT JOIN
My question is how to insert data in 2 tables using joins. For example (with php) a user can enter his/her name and the foods he/she likes.
I store them in a variable and an array (the length of the array is not always 3 like below):
$name = "Niels"
$foodsHeLikes = array("apple", "pear", "banana");
This is how I want to store them:
USERS:
UserID name
1 Niels
FOODS:
FoodID userID name //userID is linked to UserID in users table
1 1 apple
2 1 pear
3 1 banana
The link to the first question I pasted above has an insert with a join but I don't see anywhere to put the values in like with a normal insert?
The query from that question:
INSERT INTO orders (userid, timestamp)
SELECT o.userid, o.timestamp FROM users u INNER JOIN orders o ON o.userid = u.id
Judging by what's been going on in the comment section, what you're asking is that you would like to have a more optimal query process. Right now you are using two different queries to populate your two tables, and you're wondering whether that could be done more optimally.
First things first, it's not possible to populate TWO different tables with ONE query.
However, what you could do, is use transactions.
The rest of this answer will follow the assumption that you are using PHP as your backend scripting language (as you tagged yourself).
Also, it is not inherently obvious whether you use prepared statements for your queries or not. In the case you don't, I would highly recommend using prepared statements. Otherwise, you're opening yourself up to SQL Injections (SQLI Attacks).
I will proceed by using mysqli prepared statements in this answer.
<?php
// Your input post variables
$name = $_POST['name'];
$foodArray = $_POST['foodArray'];
/*
I'm using a function to handle my queries,
simply because it makes large piles of code easier to read.
I now know that every time the function:
createUserAndFood($name, $foodArray);
is called, that it will populate my user and food table.
That way I don't have to worry about writing all the code multiple times.
*/
function createUserAndFood($name, $foodArray){
// food array values
$foodValues = array_values($foodArray);
// DB variables
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
/*
Stops the query from auto commiting,
I'll explain later, you can "maybe" disregard this.
*/
$conn->autocommit(FALSE);
// Declare the query
$sql = "INSERT INTO userTable(name) VALUES(?)";
// Prepare and bind
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $name);
// Execute the query
$stmt->execute();
// Fetch last inserted id
$lastID = $conn->insert_id;
$sql = "INSERT INTO foodTable(userId, food) VALUES(?, ?)";
$stmt = $conn->prepare($sql);
for($i = 0; $length = count($foodValues) > $i; $i++){
$stmt->bind_param("is", $lastID, $food);
$food = $foodValues[$i];
$stmt->execute();
}
// Commits the query / queries
$conn->commit();
// Close connection
$stmt->close();
$conn->close();
}
?>
Since you wanted to optimize your queries, the general idea that we are using here, is that we are making use of the MySQL function LAST_INSERT_ID(); via PHP and store it into a variable.
Now, this is mainly relevant if you are using auto incremented id's. If you are not, you can disregard this specific logic and use something else. But if you are, then keep reading.
The reason why we are storing the last id into a variable is because we need to use it multiple times (the new user might have more than one favorite food afterall). If you were not to store the last id into a variable, it would instead take the auto incremented value of the second table after the initial insert, which means upon your third insert statement and forward, you would be working with the wrong id.
Now, as I promised to explain, the reason I'm using $conn->autocommit(FALSE); and $conn->commit(); is because you might not want incomplete data sets in your database. Imagine that a user input is happening, but your database crashes in the middle of it all. You'll have incomplete data sets. If this is not really a concern of yours, then you can disregard that.
To simplify what's going on at the MySQL side of things, think of it like this:
BEGIN;
INSERT userTable SET name = '$name';
SET #lastID = LAST_INSERT_ID();
INSERT foodTable SET id = #lastID, food = '$food';
COMMIT;
This code works and adds tables to my database. My question is how do I protect it with prepared statements.
require "conn.php";
$MyServer =($_POST["username"]);
$sql = ("CREATE TABLE $MyServer (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL
)");
if($conn->query($sql) === TRUE){
echo "Table created successfully";
}
I am using MySQLi.
I tryed this and it isn't adding the table.
$MyServer =($_POST["username"]);
if (!preg_match('^/[A-Za-z][A-Za-z0-9]{0,7}$/', $MyServer)) {
throw new Exception ('username unsuitable for use as a table name');
}
$sql = ("CREATE TABLE `$MyServer` (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL
)");
if($conn->query($sql) === TRUE){
echo "Table created successfully";
} else {
echo "Table is not created successfully ";
}
I guess you're thinking about how to avoid SQL injection into your query via that $MyServer variable in your sample program.
You cannot use a parameterized value to name a table (or a database, or a column) in SQL. You must do the variable substitution shown in your program.
You can use php to sanitize your $MyServer variable before you use it for subsitution though.
For example: How to check, if a php string contains only english letters and digits?
You could do this, or something like it. This requires the variable to start with a letter, then contain up to seven more characters that are letters or digits. If the variable doesn't match it throws an exception.
if (!preg_match('^/[A-Za-z][A-Za-z0-9]{0,7}$/', $MyServer)) {
throw new Exception ('username unsuitable for use as a table name');
}
Although it is questionable whether it is a good plan to allow users to create tables, to answer your question:
First of all, make sure your variable doesn't contain any strange character. Although MySQL allows (a subset of) unicode characters, you probably only want normal letters and numbers:
if (
!preg_match('/^[a-z0-9]+$/i', $MyServer)
|| preg_match(/^[0-9]+$/, $MyServer) // Identifiers may begin with a digit but unless quoted may not consist solely of digits.
|| strlen($MyServer) > 64 // Limit of table-name length
) {
// Insert your own error handling
die('Not allowed');
}
Second, to make sure SQL treat it as a identifier, quote it in backticks
$sql = "CREATE TABLE `$MyServer` (...etc..."
CREATE TABLE index (...etc... will raise an error in MySQL because index is a keyword
CREATE TABLE `index` (...etc...
wont, because it is marked as an identifier.
Honestly, you are really opening yourself up to SQL injection here by getting the data from $_POST.
Your method is a definite no go unless your usernames are already stored in your database and do not have special characters that will lead to SQL injection (such as quotations).
EDIT: I see two answers above that compliment what I have said, you could use one of those two answers (O. Jones is my preferred one).
If you want your code to be a bit more in line with PDO procedure (binding PDO values to avoid SQL injection), why not create one table with columns (username, saved_username) and you can interact with the information in that table effectively with PDO statements.
For example, all you will have to do to insert data would be:
$query = 'INSERT INTO table (username, saved_username) VALUES (:username, :username_to_save)';
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':username_to_save', $_POST['username_to_save']);
$stmt->execute()
And to select the data:
$query = 'SELECT * FROM table WHERE username = :username';
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute()
$users_saved_usernames = $stmt->fetchAll();
I have to insert data in two different database's table.
I have created database1 and table1 for database1,
also i have created database2 and table2 for database2.
For inserting data i have written code,
$connect = mysql_connect("localhost","root",""); //database connection
mysql_select_db("database1",$connect); // select database1
mysql_select_db("database2",$connect); // select database2
$sql = mysql_query("INSERT INTO database1.table1 (contact_first, contact_last, contact_email) VALUES('abc','xyz','abc#abc.com')"); //insert record to first table
$sql1 =mysql_query("INSERT INTO database2.table2 (contact_first, contact_last, contact_email) VALUES('abc','xyz','abc#abc.com')"); //insert record to second table
please suggest me corrections for above code to insert data.
Try the following code:
$connect1 = mysql_connect("localhost","root","");
mysql_select_db("database1", $connect1);
$res1 = mysql_query("query",$connect1);
$connect2 = mysql_connect("localhost","root","",true);
mysql_select_db("database2", $connect2);
$res2 = mysql_query("query",$connect2);
Note: So mysql_connect has another optional boolean parameter which
indicates whether a link will be created or not. as we connect to the
$connect2 with this optional parameter set to 'true', so both link will
remain live.
Simply connect to 1 database, insert new row, disconnect, connect to the other database, insert row into that one and disconnect.
Or you can use $connect1 and $connect2 to refer to each of them separately and do the insertion parallely.
EDIT: Btw you can select the database with the 4'th parameter of mysql_connect, no need to use mysql_select_db
And very important, you should write mysqli not mysql. Because mysql functions are not going to be supported for much longer.
first create two database connections
$connect1 = mysql_connect("localhost","root","");
$connect2 = mysql_connect("localhost","root","");
Then select the database for each connection.
mysql_select_db("database1",$connect1); // select database1
mysql_select_db("database2",$connect2); // select database2
Then pass in a second argument for mysql_query which is the respective connection for the query.
mysql_query("SELECT ... ", $connect1);
mysql_query("SELECT ... ", $connect2);
Well, if there's a pattern in db names, tables and queries are exactly the same, you can use a loop:
for ($i = 1; $i <=2; $i++) {
mysql_select_db("database".$i, $connect);
$sql = mysql_query("INSERT INTO table".$i." (contact_first, contact_last, contact_email) VALUES('abc','xyz','abc#abc.com')");
mysql_close;
}
However, using mysql_* is strongly NOT recommended, as it is deprecated from the last stable PHP release and is considered unsafe. Use PDO or MySQLi instead. PHP's official site suggests the article "Choosing an API": http://www.php.net/manual/en/mysqlinfo.api.choosing.php
Well, that's how i do it...
1 - connect --> that you are doing right
2 - check for errors
3 - USE a database (1) you want to put data in (and not 'SELECT')
4 - check for errors
5 - now INSERT items into the database THAT IS BEING USED - that is (1)
6 - check for errors
7 - USE the other database (2)
8 - check for errors
9 - INSERT the data into (2) - because that is the one in use now
10 - check for errors
Yes, be paranoid :P Hope this helps
i am trying to connect to two databases to create a search engine for a couple of my databases. Heres a test code. can someone tell me what i am doing wrong or if it is possible. thanks.
mysql_connect("localhost","user","pass");
mysql_select_db("db1");
mysql_select_db("db2");
$search=mysql_query("SELECT * from db1.repairs, db2.order from db1,db2");
while($row=mysql_fetch_array($search)){
echo $row['first_name']." ".$row['esn']." ".$row['order_type']."<br>";
}
You can query across databases if you specify the database name before the table name like this
SELECT a.col1, b.col2
FROM db1.table1 AS a
INNER JOIN db2.table2 AS b ON a.someIdFromA = b.someIdFromB
As Korcholis mentions the problem is in your select. Also you do not want to use the mysql_* functions if you can avoid it. PDO or MySqli are preferred.
Edit
At least this works using MySQL. I would bet it works for most other RDBMSes as well, but I don't have others handy to test and I can't say if this conforms to SQL standards or not. Comments anyone?
You can use
<?php
$db1 = mysql_connect("localhost","user","pass");
$db2 = mysql_connect("remote","user","pass");
mysql_select_db("db1", $db1);
mysql_select_db("db1", $db2);
$query1 = mysql_query("USE somedatabase", $db1);
$query2 = mysql_query("USE otherdatabase", $db2);
Or try with a class that handles these connections in a different instances
http://www.joni2back.com.ar/programacion/php-class-for-mysql-databases/
mysql_connect returns a $resource. You can connect twice and select a database with each one (in fact, you can select a database from the connect itself), and then use each connection.
However, your problem is that your SELECT is incorrect. You are trying to select fields from tables from databases, which is not correct. In fact, you cannot fetch two different databases in a so fancy way, because they are considered two sets of information independent and unrelated between them. That's why tables exist, to fit that problem.
This other answer, however, may have a solution.
Otherwise, you could connect to each database using two mysql_connect and two resources, fetch the values, and cross them yourself. Not the best option, I know, but an answer that could fit your needs.
PS: If you are beginning the project right now, switch to Mysqli or PDO. Mysql is deprecated.
Try to review this, and maybe you can't query a database with querying FROM:
<?php
$con1 = mysqli_connect("$hostname", "$user1", "$password1", "$db1");
if (mysqli_connect_errno($con1)) {
echo mysqli_connect_error();
}
$con2 = mysqli_connect("$hostname", "$user2", "$password2", "$db2");
if (mysqli_connect_errno($con2)) {
echo mysqli_connect_error();
}
$search1 = mysqli_query($con1, "SELECT * from $db1table");
$search2 = mysqli_query($con2, "SELECT * from $db2table");
/* Other PHP codes here */
mysqli_close($con1);
mysqli_close($con2);
?>
You can even improve this code, nor minimized it!
I added to a database a new table using PHPMyAdmin; when trying to access it from a PHP page I get the dreaded MySQL error "table doesn't exist".
Database connection data are OK, they are used a few lines above on the same page to access another table in the same database. If I do SHOW TABLES in PHPMyAdmin the new table is listed; if I do it from a PHP page the new table does not appear in the list.
Engine for the new table is MyISAM, like all other tables in the database. I can access the db server only via PHPMyAdmin.
Sorry, I forgot the code, here it is:
$db = mysql_connect ($db_host, $db_user, $db_password) or
die("Error message here");
$db_select = mysql_select_db($db_name, $db)or die("Error message here");
$query = ("SELECT * FROM `old_table`");
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
// do stuff - here it works
}
$query = ("SELECT * FROM `new_table`");
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
// do stuff - here it does not work
echo mysql_error();
}
On Unix, table names are case sensitive. On Windows, they are not. Fun, isn't it? Kinda like their respective file systems. Do you think it's a coincidence?
It probably depends on table type; MyISAM in your case.
Field names are case-insensitive regardless.
For database and table names, it depends on the underlying operating system. Identifier Case Sensitivity
The answer is simple: some typo or another silly mistake like this: you're connecting wrong server, editing wrong file or something of the kind. Just double check everything.
There is no particular error to cause this
The answer is: the table name or at least one of the field names is a reserved word.
To solve it, you can enclose the fields and table name with grave accents (`), e.g:
SELECT `value` FROM `pivot`;