I am having problems with writing correct MySql query. I want to insert new collection for every user with id higher than 1000 but less than 10000.
$conn = $this->em->getConnection();
$stmt = $conn->prepare('INSERT INTO collection (name, type)
values(:name, :type)
SELECT * FROM user WHERE id<:endUser AND id>:startUser');
$stmt->bindValue('name', 'Default');
$stmt->bindValue('type', 0);
$stmt->bindValue('startUser', 1000);
$stmt->bindValue('endUser', 10000);
$stmt->execute();
This what I tried to write, but I get syntax error. Please explain me how to correct query
UPD
I should have given detailed structure of tables.
Collection
CREATE TABLE IF NOT EXISTS `collection` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`type` smallint(6) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_FC4D6532A76ED395` (`user_id`)
);
User
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);
User has one-to-many relationship with Collection.
With a SELECT INTO you have to select the values you want to place in the new row and only those values. And you dont use the VALUES() clause.
As you are using static values for the new rows and not values from the user table you can do it like this.
Oh and I see in your edit you were using the wrong table name It should have been fos_user
Also as fos_user.user_id is a NOT NULL field you need to include that column in the list of fields in the insert.
$conn = $this->em->getConnection();
$stmt = $conn->prepare('INSERT INTO collection (user_id, name, type)
SELECT id, 'default', 0
FROM fos_user
WHERE id > :startUser AND id < :endUser');
$stmt->bindValue('startUser', 1000);
$stmt->bindValue('endUser', 10000);
$stmt->execute();
Related
I have a online page which will allow user to create an account for them in order to acceess our page.
I worry in some period, there will be a lots of user who create at the same time.
In that case, I worry my database will be clash or conflict.
Can I know is that anyway to prevent that happens?
My table as below:
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`userid` varchar(30) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`name` varchar(40) DEFAULT NULL
)
ALTER TABLE `user`
ADD PRIMARY KEY (`id`);
ADD UNIQUE KEY `userid` (`participant_id`);
ALTER TABLE `user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;
So my id will be just number and auto increment.
userid wil be unique.
I created the page by using PHP.
And I use following insert command at my page:
do {
$query = "INSERT IGNORE INTO user(userid, password, name) VALUES ('$userid','$password','$name')";
$insert = $conn->query($query);
} while( $insert && ($conn -> affected_rows == 0) );
Are this code can work perfectly to prevent the date conflit?
Another extra question is, how about if I create another extra page which will insert information 'user' table and can I used the same code at the new page?
I have a very strange problem with MySQL and PHP.
I have into a function the below query:
Global $Linker;
$query = "INSERT INTO ".$user_type." (id) VALUES (?)";
if($stmt = mysqli_prepare($Linker->DataBase,$query)) {
mysqli_stmt_bind_param($stmt,"i",$max_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
} printf("Error: %s.\n", mysqli_stmt_error($stmt));
where
$Linker is the variable that holds the database connection
and
$user_type is the table I want to insert in the database
I get the following error printed
Error: Cannot add or update a child row: a foreign key constraint fails (std10179db/Students, CONSTRAINT fk_Students_Users1 FOREIGN KEY (id) REFERENCES mydb.Users (Table_ID) ON DELETE NO ACTION ON UPDATE NO ACTION).
The problem is that when I run the same query directly in MySQL through command line in the server it works as expected with no errors.
I found a work around using:
$query= "SET FOREIGN_KEY_CHECKS=0";
$stmt = mysqli_prepare($Linker->DataBase,$query);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
before my query in the PHP function and another workaround would be to change my database schema
but I want to know why that is happening?
I have even tried to execute the query without parameters:
$query = "INSERT INTO Students (id) VALUES (3)";
to be exactly the same with the one I put directly into the server with no success.
Any ideas?
edit:
Table USERS
CREATE TABLE `std10179db`.`Users` (
`ID` INT NOT NULL ,
`Username` VARCHAR(45) NOT NULL ,
`Password` VARCHAR(45) NOT NULL ,
`email` VARCHAR(45) NOT NULL ,
`User_Class` VARCHAR(45) NOT NULL ,
`Table_ID` INT NOT NULL ,
PRIMARY KEY (`ID`) ,
UNIQUE INDEX `Username_UNIQUE` (`Username` ASC) ,
UNIQUE INDEX `Password_UNIQUE` (`Password` ASC) ,
UNIQUE INDEX `email_UNIQUE` (`email` ASC) )
ENGINE = InnoDB;
and Table Students
CREATE TABLE `std10179db`.`Students` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`Univ_ID` VARCHAR(45) NULL ,
`Name` VARCHAR(45) NULL ,
`Surname` VARCHAR(45) NULL ,
`Telephone` VARCHAR(45) NULL ,
`Semester` INT NULL ,
`Department_id` INT UNSIGNED NULL ,
PRIMARY KEY (`id`, `Department_id`) ,
UNIQUE INDEX `idStudents_UNIQUE` (`id` ASC) ,
INDEX `fk_Students_Department1` (`Department_id` ASC) ,
CONSTRAINT `fk_Students_Department1`
FOREIGN KEY (`Department_id` )
REFERENCES `mydb`.`Department` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Students_Users1`
FOREIGN KEY (`id` )
REFERENCES `mydb`.`Users` (`Table_ID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I have the following table structure:
CREATE TABLE IF NOT EXISTS `reports` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`day` int(11) NOT NULL,
`uid` int(11) NOT NULL,
`siteid` int(11) NOT NULL,
`cid` int(3) NOT NULL,
`visits` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
Currently i check & insert/update with the following snippet:
$checkq = mysql_query("SELECT count(*) as rowexist FROM reports WHERE day='$day' AND uid='$uid' AND siteid='$sid' AND cid='$cid'") or die(mysql_error());
$checkr = mysql_fetch_array($checkq);
if ($checkr['rowexist'] > 0) {
mysql_query("UPDATE reports_adv SET visits=visits+1 WHERE day='$day' AND uid='$uid' AND siteid='$sid' AND cid='$cid'");
} else {
mysql_query("INSERT INTO reports_adv SET day='$day', uid='$uid', siteid='$sid', cid='$cid', visits='1'");
}
Is a fastest way to update this MySQL table if row exists else insert with more than 2 non-unique keys?
just use INSERT...ON DUPLICATE KEY UPDATE
INSERT INTO reports_adv (day, uid, siteid, cid, visits)
VALUES ('$day', '$uid', '$sid', '$cid', 1)
ON DUPLICATE KEY UPDATE visits=visits+1;
INSERT ... ON DUPLICATE KEY UPDATE Syntax
but before anything else, you should define a UNIQUE constraint on the columns.
ALTER TABLE reports_adv ADD CONSTRAINT tb_uq UNIQUE (day, uid, siteid, cid)
I have developed a script using Yii MVC and i have a problem with the index keys and criterias.
I want to prevent the insertion of a record that is already stored in the database;
My example, fails to check and tries to add a new record each time.
Why ? And how to do this ?
CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21-/popular/category/1.html' for key 'index_link'. The SQL statement executed was: INSERT INTO `categories` (`server_id`, `website_id`, `slave_category_id`, `link`, `name`, `image`, `videos`, `status`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, :yp7)
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) NOT NULL,
`website_id` int(11) NOT NULL,
`slave_category_id` int(11) NOT NULL,
`link` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`image` varchar(255) NOT NULL,
`videos` int(11) NOT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `index_link` (`website_id`,`link`),
UNIQUE KEY `index_name` (`website_id`,`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=332 ;
the PK is id;
another index, is website_id + link;
another index is website_id + name;
the following code fails to check and prevent the insertion:
1
$criteria_categories = new CDbCriteria();
$criteria_categories->condition = " `server_id`=':server_id' and `website_id`=':website_id' and `link`=':link' and `name`=':name' ";
$criteria_categories->params = array(
':server_id' => $model_website->server_id,
':website_id' => $model_website->id,
':link' => $matches_url[$value->link][$key2],
':name' => $matches_url[$value->name][$key2],
);
$record_categories = Categories::model()->find($criteria_categories);
print_r($record_categories);
if (!$record_categories) {
$model_categories = new Categories();
$model_categories->server_id = $model_website->server_id;
$model_categories->website_id = $model_website->id;
$model_categories->slave_category_id = 1; //??
$model_categories->link = $matches_url[$value->link][$key2];
$model_categories->name = $matches_url[$value->name][$key2];
$model_categories->image = $matches_url[$value->image][$key2];
$model_categories->videos = 0;
$model_categories->status = 0;
$model_categories->save();
}
$criteria_categories->condition = " `server_id`=':server_id' and `website_id`=':website_id' and `link`=':link' and `name`=':name' ";
You have a couple errors going on. One is syntax. If using the parameter binding (which is a good thing to use), you don't want to quote the parameters.
That is, write :link instead of ':link'.
The above condition also does not correctly check for existing records that have either of your two unique keys. Try the following:
$criteria_categories->addCondition("`server_id`=:server_id AND `website_id` = :website_id
AND (`link`=:link OR `name` = :name)");
This both quotes correctly and will find the record if either of your two unique keys match, rather than requiring both to match.
I'm having trouble inserting image data into my database. I have a table called images. When dumped with PHPMyAdmin it looks like this:
CREATE TABLE IF NOT EXISTS `images` (
`id` int(11) NOT NULL,
`orig_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`hash` varchar(6) COLLATE utf8_unicode_ci NOT NULL,
`filename` varchar(12) COLLATE utf8_unicode_ci NOT NULL,
`uploaded` datetime NOT NULL,
`views` int(11) NOT NULL DEFAULT '0',
`album_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`server_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `server_id` (`server_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
This is the code I'm using to insert rows:
// Database connection
$db = new PDO('mysql:host=localhost;dbname=testdb', 'root', '');
// some code...
$st = $db->prepare('INSERT INTO `images` (orig_name, hash, filename, uploaded, server_id)
VALUES (?, ?, ?, ?, (SELECT `id` FROM `servers` WHERE `name` = ?))');
$st->execute(array($origName, $fileHash, $filename, date('c'), $server));
// more code...
// Database cleanup
$st = null;
$db = null;
The script returns no errors, and works flawlessly for the first row inserted. If the script runs again, it fails to insert any more rows in the images table. I see no reason why it'd behave like this, the data going into each field is unique each time (except for the server_id field).
Your id field isn't set to auto_increment.
The first record that you post will be added, with a NULL as id; the second record won't be added because there's already a record with NULL as the primary key, so it'll fail - you don't have any error checking in the code, so it won't be printing out the errors it's getting back.