php can't create new database tables via query - php

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.

Related

In a 1-1 relationship, why is my insert inserting two records in two tables?

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!

Run multiple CREATE TABLe queries with MySQL and PHP

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.

update then replace dies

If there is a row for user_id then I want to update, if not insert (but I was told to use replace). In the table there is id (which is primary key, auto inc) and user_id (index, session relates to). I have a form that when the data is changed it should be changed in the database for that particular user in session, otherwise it is just added for that particular user in session
if (empty($err)) {
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
$query="UPDATE thesis SET thesis_Name ='$thesis_Name',
abstract='$abstract' WHERE id='$_SESSION[user_id]'
IF ROW_COUNT()=0
REPLACE INTO thesis (thesis_Name,abstract)VALUES ('$thesis_Name', '$abstract')
";
mysql_query($query) or die();
// query is ok?
if (mysql_query($the_query, $link) ){
// redirect to user profile
header('Location: myaccount.php?id=' . $user_id);
}
With this the page just dies.
EDIT:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
Thanks so much
You don't need to do the UPDATE first - REPLACE handles all of this for you. From the MySQL manual:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2.5, “INSERT Syntax”.
Therefore, so long as id is a unique key in your thesis table, the only SQL you need is:
REPLACE INTO thesis (id, thesis_Name, abstract)
VALUES ('$_SESSION[userid]', '$thesis_name', '$abstract');
There are a few things in your code that pose problem. First you don't have to do an insert and a replace in the same query : replace will insert if there is no row to replace (besides, I'm not even sure the sql syntax you're using is correct)...
Then you do a mysql_query($query) or die() which is probably where your code dies (maybe due to the fact that the sql syntax you used could be incorrect).
Right after that, you do a mysql_query again, which would reexecute the query a second time. Anyway, if your query didn't work, your code would have died on the previous line...
What you could do would be
$query = "REPLACE INTO blablabla";
if (!mysql_query($query))
echo "the query failed";
else header ("location:blabla");
but your query should mention for which user_id you want to update like this
REPLACE INTO thesis (id, thesis_Name, abstract)
VALUES ('{$_SESSION[userid]}', '$thesis_name', '$abstract');
INSERT
INTO thesis (id, abstract, thesis)
VALUES ('$_SESSION[user_id]', '$abstract', '$thesis_Name')
ON DUPLICATE KEY
UPDATE
abstract = VALUES(abstract),
thesis_Name = VALUES(thesis_Name)
You can do it with prepared statements.You can see an example sql ;
DROP PROCEDURE IF EXISTS `UPDATETHESIS`
|
CREATE PROCEDURE `UPDATETHESIS` (IN _id VARCHAR(50), IN _thesis_name VARCHAR(50), IN _abstract VARCHAR(50))
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY INVOKER
IF EXISTS (SELECT * FROM thesis WHERE id = _id)
BEGIN
UPDATE thesis SET thesis_Name = _thesis_name,
abstract = _abstract WHERE id = _id
END
ELSE
BEGIN
INSERT INTO thesis (thesis_Name,abstract) VALUES (_thesis_name, _abstract)
END
You can call this like CALL UPDATETHESIS(userid, thesis_name, abstratc);

set ID value for another field

Can I set the model record ID for another field value? (without update it)
In the other way, mix this code to one or two line:
$this->Model->create($data);
$this->Model->save();
$this->Model->create($data); // create again
$this->Model->set('link', $this->Model->id); // get record id
$this->Model->save(); // update
Thanks.
Yes, but you need to make the proper calls to the proper model methods. You will also need to make certain you are storing the information correctly in the array you are passing to save. So let's say you are adding a record to the places table. Let's say your schema looks like this:
CREATE TABLE 'places' (
`id` CHAR(36) NOT NULL,
`reference_id` CHAR(36) NULL,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
);
Then you have the following:
$data['Place']['name'] = 'New York';
// create the first record to get the PK ID that will
// be used in the reference_id of the next record
$this->Place->create();
$this->Place->save($data);
// set the reference ID to the ID of the previously saved record
$data['Place']['reference_id'] = $this->Place->id;
// create the next record recording the previous ID as
// the reference_id
$this->Place->create();
$this->Place->save($data);

SQL Create multiple tables at once

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

Categories