I need to create multiple tables at once. Im having a hard time figuring out the correct method for accomplishing this. Currently my script looks like this:
private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS headings (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
CREATE TABLE IF NOT EXISTS titles (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
Obviously, this doesn't work and no tables are created. Is there a simple way for creating multiple tables at once?
MySQL is getting confused because you're not delimiting your queries. Add a semicolon after the first CREATE statement:
private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS headings (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
);
CREATE TABLE IF NOT EXISTS titles (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
Also, make sure MySQL_QUERY is at the beginning of the line with no other characters, except maybe a semicolon, as per the Heredoc documentation.
Seeing as the above doesn't appear to work, give this code a try:
private function buildDB() {
$sql1 = "CREATE TABLE IF NOT EXISTS headings (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100))";
$sql2 = "CREATE TABLE IF NOT EXISTS titles (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100))";
MySQL_QUERY;
return mysql_query($sql1) && mysql_query($sql2);
}
You could use mysqli_multi_query() (the MySQL version doesn't exist), but you'd have to use MySQLi then. The above code returns the logical AND of the two queries, so you still get a 0 returned if one fails.
You can issue multiple queries as long as they are properly delimited. When issuing multiple queries, change this:
CREATE TABLE IF NOT EXISTS headings (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
CREATE TABLE IF NOT EXISTS titles (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
to
CREATE TABLE IF NOT EXISTS headings (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
); // added a friendly semicolon
CREATE TABLE IF NOT EXISTS titles (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
); // added a friendly semicolon
and you should be set.
If not, throw some debugging in there to see exactly where your SQL or surrounding code is unhappy.
It is because mysql_query() can execute only a single query at a time. Please try using mysqli::multi_query() instead (http://php.net/manual/en/mysqli.multi-query.php) but do end your queries with a semi-colon.
The simplest approach however is to directly run the CREATE TABLE statements in your MySQL client
Related
I'm having trouble, as title says, when I INSERT a record in a table that has got a 1-1 relationship with another.
First things first, the SQL code that generates the tables:
DROP TABLE IF EXISTS Facebook_Info;
DROP TABLE IF EXISTS Conversations;
CREATE TABLE IF NOT EXISTS Conversations(
c_id INT AUTO_INCREMENT NOT NULL,
c_start TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
channel ENUM('desktop', 'facebook'),
u_name VARCHAR(20) DEFAULT NULL,
u_email VARCHAR(50) DEFAULT NULL,
PRIMARY KEY(c_id)
);
CREATE TABLE IF NOT EXISTS Facebook_Info (
c_id INT AUTO_INCREMENT NOT NULL,
f_id INT(12) NOT NULL,
PRIMARY KEY(c_id),
FOREIGN KEY(c_id) REFERENCES Conversations(c_id)
);
I assure you this code works: I tested it. I hope this is the best way to provide a 1-1 relationship between Conversations and Facebook_Info.
In any case, now I can introduce you my nightmare: I'm trying to insert a new record in Conversations via PHP (procedural style).
public function create_new_id_conv($channel = 1) {
$w_ch = '';
if ($channel == 2) {
$w_ch = 'facebook';
} else {
$w_ch = 'desktop';
}
$query = "INSERT INTO Conversations (c_id, c_start, channel) VALUES (NULL, CURRENT_TIMESTAMP,'$w_ch')";
$conn = mysqli_connect("localhost", Wrapper::DB_AGENT, Wrapper::DB_PSW, Wrapper::DB_NAME);
$res = mysqli_query($conn, $query);
$id_conv= mysqli_insert_id($conn);
mysqli_free_result($res);
return $id_conv;
}
The Wrapper:: * variables are all set well, in fact, an INSERT operation is done, but not only one! I'm having this situation after I call this function:
This is the content of Conversations table:
And here's the content of Facebook_Info:
What's happening?
I searched and searched...
Then I started to think about what I'm getting here: 2147483647. What represents this number? What's that? Seems like a big number!
And what if my script and my queries were correct but the mistake is the skeleton of my tables?
I must register a 14 digit integer, that is too large for the INT type.
So using BIGINT to store the f_id field made all correct and working!
Hope my mistake helps someone!
I need to create a large number of tables at once and add data to the first one using PHP and MySQL. My code looks like this:
$sql = "CREATE TABLE table1 (
code VARCHAR(5) PRIMARY KEY,
name VARCHAR(50) NOT NULL
);";
//adding businesses to table
$sql .= "INSERT INTO table1 (code, name)
VALUES ('CODE', 'name');";
//^this basic idea is run a few more times
$sql .= "CREATE TABLE table2 (
code VARCHAR(5) PRIMARY KEY,
name VARCHAR(50) NOT NULL
);";
//^same basic thing run a bunch more times w/ variations to columns
if ($conn->multi_query($sql) === TRUE) {
echo "<p>Tables created.</p>
Continue";
} else {
echo "<p>Error creating tables: " . $conn->error . "</p>";
}
This only creates the first table and adds the data to it, it won't create any other tables and I get no error messages (the success message is shown). I've been googling a solution for an hour and I can't come up with anything. I'm thinking I need a way to hold off creating the next table until the previous one has been created?
I'm very new to MySQL so newbie-friendly would be very much appreciated:)
Try using backticks in your SQL statements, such as:
$sql .= "CREATE TABLE `table2` (
`code` VARCHAR(5) PRIMARY KEY,
`name` VARCHAR(50) NOT NULL
);";
You should also use backticks in your INSERT statement (and your first CREATE query).
If I'm not mistaken, name is reserved word.
I have this MySQL Structure:
CREATE TABLE Fields (
ID INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ForUser VARCHAR(255) NOT NULL,
ForCategory VARCHAR(100) NOT NULL,
FieldName VARCHAR(100) NOT NULL
);
CREATE TABLE Content (
ID INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ForUser VARCHAR(255) NOT NULL,
ForCategory VARCHAR(100) NOT NULL,
ForField VARCHAR(100) NOT NULL,
FieldContent VARCHAR(255) NOT NULL
);
Now I want to make SQL Query that list results in HTML Table. As Head Table I want to list FieldName from Fields, and as Table Body I want to list FieldContent from Content. Also in WHERE clause must be ForUser AND ForCategory... to list Content for each field. I'm tried with SQL Join, but I'm spend 3 hours without success. Can, please, someone write me an example how to display this.
If I understand this request correctly (you're a little light on detail), you will need a use a few components to achieve your goal:
Two sql queries (one for the table header and one for the table body)
Some php or another scripting language to display your results as html.
Your first query will just bring back the field names, filtered by user and category:
select ID, FieldName from Fields where ForUser = 'some_user' and ForCategory = 'some_category' order by ID;
IN your php or other code, you need to iterate through the results and display each result wrapped in the html tags, eg:
echo '<table><tr>';
$fields = # mysql_query ("select ID, FieldName from Fields where ForUser = 'some_user' and ForCategory = 'some_category' order by ID;", $connection);
while ($fields_result = mysql_fetch_assoc($fields)) {
echo '<th>' . $fields_result['FieldName'] . '</th>;
}
echo '</tr>';
Then run a second sql query to bring back the contents:
select
FieldContent
from
Content c join
Fields f on
c.ForField = f.FieldName and
c.ForUser = f.ForUser and
c.ForCategory = f.For Category
where
f.ForUser = 'some_user' and
f.ForCategory = 'some_category'
order by ID;
And in a similar fashion, iterate through the results in php to build the content rows in the table.
Note that I'm ordering on the PK in the Fields table to ensure that the content comes back in the same order as the fields. This approach might not suffice, you may need to add a "sequence" field if you need a specific field order.
Also note my prevous comment that you would do well to revise your database structure. You don't need to repeat all the fields in the Content table, you can just add a foreign key referencing the ID of the Field record
Table join query:
SELECT
a.ID,
a.ForUser,
b.ForUser,
a.ForCategory,
b.ForCategory,
a.FieldName,
b.ForField,
b.FieldContent
FROM
Fields a,
Content b
WHERE
a.ForUser = '' AND b.ForCategory = ''
I have set up four additional tables for my plugin to use what I am trying to do is take a name and assign it a ID then use this data to populate drop down menus with a name and the same for class and position I am unsure as to how to do this correctly this is what i have so far.
$sql = "CREATE TABLE $tableName (
recordID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(recordID),
driverID int,
driverName varchar(30),
classID int,
driverClass varchar(20),
posID,
driverPosition varchar(6),
trackName varchar(30),
raceDate date
);";
$sql = "CREATE TABLE $driverTableName (
driverID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(driverID),
driverName varchar(30)
);";
$sql = "CREATE TABLE $classTableName (
classID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(classID),
className varchar (20)
);";
$sql = "CREATE TABLE $posTableName (
posID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(posID),
posName varchar(6)
);";
The bottom three tables will store the data I want to populate the drop down boxes to create a record with I am unsure as to how to link them to the top table where this record will be stored.
This is pretty much a indexing issue. If you are going to access the database separately to the standard calls that Wordpress provides, you should at the very least use http://codex.wordpress.org/Class_Reference/wpdb as it will save you some coding time.
The rest of it is a MySQL question. (Assuming you are using MySQL) In how to properly index the data together and then parsing the data as it comes in.
Here is the code that should create 2 new tables in MySQL if they do not exist CMS and PAGES, however what is occurring is that CMS is being created but PAGES is ignored and is not created.
Here is the php function responsible for creating tables
private function buildDB() {
#lets create cms table if one does not exist
$make_cms = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS cms (
title VARCHAR(150),
bodytext TEXT,
date VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($make_cms);
#lets create pages table if one does not exist
$make_pages = <<<MySQL_QUERY2
CREATE TABLE IF NOT EXISTS pages (
pid int NOT NULL AUTO_INCREMENT, PRIMARY KEY (pid),
title VARCHAR(150),
text TEXT,
date VARCHAR(100)
)
MySQL_QUERY2;
return mysql_query($make_pages);
}
And there ya go that's the function. I ones again will note part one of it works so there for $make_cms does its job and actually makes a table called CMS while the function $make_pages does nothing and fails to create PAGES table.
You're returning from the function before beginning the second CREATE TABLE statement. You'll therefore never reach the second statement.
// Don't return here!
return mysql_query($make_cms);
Instead assign the value and return only if FALSE:
$success_cms = mysql_query($make_cms);
// Return only on error of first table creation
if (!$success) {
return FALSE;
}
// Then create the second table...
If you use echo mysql_error() to output the error, it will tell you. I would guess it is because you have a field named text, which is a reserved word. Try escaping your field names in tics ( ` ) or avoiding reserved words.
#lets create pages table if one does not exist
$make_pages = <<<MySQL_QUERY2
CREATE TABLE IF NOT EXISTS pages (
`pid` int NOT NULL AUTO_INCREMENT, PRIMARY KEY (`pid`),
`title` VARCHAR(150),
`text` TEXT,
`date` VARCHAR(100)
)
MySQL_QUERY2;
The query itself seems OK, so one explanation may be that either pages exists already, or the user somehow has no permission to create that particular table.
You can modify your code so it shows what the MySQL server said when running the query:
result = mysql_query($make_pages);
if (!$result) {
echo('Invalid query: ' . mysql_error());
}
change "text TEXT," to text1 TEXT and it should work! remember sql is not case sensitive.