get the foreign key [duplicate] - php

This question already has answers here:
MYSQL - Impossible to create an external key
(1 answer)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
I am a self taught programmer in college and I am super confused since few days. I am working on the backend of a job listing website. The user will be able to post a job and I have three tables: jobs, keywords and requirements. The job_id is the primary key of jobs and also a foreign key in the keywords table. Right now, I am only able to insert data in the jobs table and I am not able to key anything from the keywords table. Each job_id can have multiple keyword.
SQL - jobs table
CREATE TABLE `jobs` (
`title` text NOT NULL,
`type` text NOT NULL,
`location` text NOT NULL,
`salary` int(11) NOT NULL,
`description` text NOT NULL,
`date` date NOT NULL,
`job_id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=latin1;
SQL - keywords table
CREATE TABLE `keywords` (
`keyword_id` int(11) NOT NULL AUTO_INCREMENT,
`keyword` text NOT NULL,
`job_id` int(11) NOT NULL,
PRIMARY KEY (`keyword_id`),
KEY `job_id` (`job_id`),
CONSTRAINT `keywords_ibfk_1` FOREIGN KEY (`job_id`) REFERENCES `jobs` (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;
PHP (I know the code is not secured yet but I just want to understand first)
<?php
require("../config/db.php");
require("add-jobs.php");
$link = mysqli_connect("localhost","root","","benoit");
$title = $_POST["position"];
$type = $_POST["job-type"];
$location = $_POST["location"];
$salary = $_POST["salary"];
$description = $_POST["description"];
$date = $publisheddate;
$keywords = $_POST["keywords"];
mysqli_query($link,"INSERT INTO jobs (`title`, `type`, `location`, `salary`, `description`, `date`)
VALUES ('$title', '$type', '$location', '$salary', '$description', CURDATE())")
or die(mysqli_error($link));
foreach ($keywords as $keyword){
mysqli_query($link, "INSERT INTO keywords (`keyword`) VALUES ('$keyword')");
}
?>

Get insert id with $mysqli->insert_id and use it:
mysqli_query($link, ".....");
$insert_id = mysqli_insert_id($link);
foreach ($keywords as $keyword){
mysqli_query($link, "INSERT INTO keywords (`job_id`, `keyword`) VALUES ($insert_id, '$keyword')");
}

Related

Mysql Create Table If Not Exists else.... Information Schema

Quick one hopefully - not sure where I'm going wrong here but this doesn't seem to work full stop.
Running MySQL query through PHP...
Current code
$uu = mysql_query("
IF EXISTS(SELECT table_name FROM information_schema.tables
WHERE table_schema = 'schema_example' AND table_name = 'test_q')
THEN
insert into `test_q` (code, va_desc, price, category)
values ('$code', '$desc', '$price', '$categ')
on duplicate key update va_desc='$desc', price='$price', category='$categ'
ELSE
CREATE TABLE `test_quote` (
`code` varchar(30) NOT NULL,
`va_desc` text NOT NULL,
`price` text NOT NULL,
`category` text NOT NULL,
PRIMARY KEY (`code`),
UNIQUE KEY `id` (`code`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
insert into `test_q` (code, va_desc, price, category)
values ('$code', '$desc', '$price', '$categ')
END IF;
")or die(mysql_error());
Really appreciate some help on what I need to change, at the moment this does absolutely nothing and doesn't return any specific errors. :/
Having said that if I run it in phpMyAdmin it returns the following (although I can't understand why):
#1064 - 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
'ELSE CREATE TABLE `test_quote`(
`code` varchar(30) NOT NULL,
`va_desc` text NO' at line 7
You don't need to query INFORMATION_SCHEMA. You can use the IF NOT EXISTS option to CREATE TABLE.
mysql_query("CREATE TABLE IF NOT EXISTS `test_q` (
`code` varchar(30) NOT NULL,
`va_desc` text NOT NULL,
`price` text NOT NULL,
`category` text NOT NULL,
PRIMARY KEY (`code`),
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1");
mysql_query("insert into `test_q` (code, va_desc, price, category)
values ('$code', '$desc', '$price', '$categ')
on duplicate key update va_desc='$desc', price='$price', category='$categ'");
Also, a primary key is a unique key, you don't need to specify them both when you create the table.
Trying using the following query as if, else and then statements are not supported in the sql query, for that you can stored procedures.
mysql_query("CREATE TABLE IF NOT EXISTS `test_q` (`code` varchar(30) NOT NULL,
`va_desc` text NOT NULL,
`price` text NOT NULL,
`category` text NOT NULL,
PRIMARY KEY (`code`),
);
mysql_query("insert into `test_q` (code, va_desc, price, category)
values ('$code', '$desc', '$price', '$categ')
on duplicate key update va_desc='$desc', price='$price', category='$categ'");

Symfony2 MySQL: INSERT SELECT syntax error

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();

How to check if column 1 has two different values for column 2

I am trying to make a INSERT by UNIQUE and I am getting stuck, What I want too know is how I would do is make it so Column A is ALWAYS UNIQUE unless Column C has two different values and then it will insert into the database a second row for Column A where Column C is different.
a|b|c
-----
1|2|3
2|4|5
1|6|7
So I am currently using this sql table
CREATE TABLE `Player` (
`id` int(11) NOT NULL auto_increment,
`playername` varchar(255) NOT NULL,
`SteamID` varchar(255) NOT NULL UNIQUE,
`position` varchar(255) NOT NULL,
`lastlogin` varchar(255) NOT NULL,
`approved` varchar(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
With this query
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
It inserts the way I want so there is only 1 of each SteamID but it also will not insert if the same SteamID has two values for position.
EDIT:
What I have is a xml file I load up and insert data into the database based on the data in the xml file, What I need is below.
$xml = simplexml_load_file("players.xml");
foreach($xml->children() as $player)
{
$id = $player->attributes()->id;
$profile = new SteamProfile($id);
$name = mysql_real_escape_string($profile->getUsername());
$lastlogin = $player->attributes()->lastlogin;
$position = $player->lpblock->attributes()->pos;
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
if (!mysql_query($sql1,$connection))
{
die('Insert Error: ' . mysql_error());
}
}
so the xml file gets read and then the data in the file gets inserted into the database. sometimes the xml file would contain
<player id="76561197961716203" lastlogin="8/22/2014 10:49:28 PM">
<acl id="76561197961543041"/>
<acl id="76561197988417990"/>
<lpblock pos="273,93,-102"/>
<lpblock pos="1322,62,-1711"/>
</player>
at which point I would need a second row created for the second <lpblock pos=
So its currently inserting
|60|SwordFish |76561197961716203|273,93,-102|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
and it should be inserting
|60|SwordFish |76561197961716203|273,93,-102|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
|61|SwordFish |76561197961716203|1322,62,-1711|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
I'm not sure what you are trying to achieve, but you can set a UNIQUE restraint on a combination of columns, in your case SteamID and position:
CREATE TABLE `Player` (
`id` int(11) NOT NULL auto_increment,
`playername` varchar(255) NOT NULL,
`SteamID` varchar(255) NOT NULL,
`position` varchar(255) NOT NULL,
`lastlogin` varchar(255) NOT NULL,
`approved` varchar(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_combination_of_two_fields` (`SteamID`,`position`)
) ENGINE=InnoDB;
Thanks for you help Jeroen I did this and its working.
foreach($player->children() as $lpblock)
{
$position = $lpblock->attributes()->pos;
if(!empty($position))
{
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
if (!mysql_query($sql1,$connection))
{
die('Insert Error: ' . mysql_error());
}
}
}
However I would like all of the SteamID's inserted and not just the ones with a $position set. When I take this out and try it adds the correct rows but also adds another row with a blank $position as if there is a SteamID that's blank when there is none.
if(!empty($position)){
}

Wrong Value showing in echo after request

I am trying to make a team name shown from a URL pulling information from my database regarding that team
<?
$query = "select * from teams where
name='".$mysqli->real_escape_string($_REQUEST['name'])."'";
$result = $mysqli->query( $query );
$row = $result->fetch_assoc();
$id = $row['id'];
$name = $row['name'];
$lon = $row['lon'];
$lat = $row['lat'];
$distance = $row['distance'];
$postcode = $row['postcode'];
$phone = $row['phone'];
?>
This worked fine until I put a second team name in the database and now all pages shows that name
the URL is http://domain.com/team.php?name=Test%20TeamA
and its showing Test TeamB and not the required one above
I have checked this on 2 pc's just to make sure its not something wrong with my form i used to put the data into my database or any values hanging about in my browser
why is this doing it?
SQL DUMP
--
-- Table structure for table `teams`
--
CREATE TABLE IF NOT EXISTS `teams` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`lat` varchar(32) NOT NULL,
`lon` varchar(32) NOT NULL,
`distance` varchar(20) NOT NULL,
`postcode` varchar(20) NOT NULL,
`phone` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `teams`
--
INSERT INTO `teams` (`id`, `name`, `lat`, `lon`, `distance`, `postcode`, `phone`) VALUES
(1, 'Test TeamA', '52.483038', '0.178962', '12.9', 'PE15 0JJ', ''),
(3, 'Test TeamB', '52.45645', '0.823423', '12', '', '01231223');
This is not the idea answer for a question like this but please see all the replies under my question
In my case it was a error on another page that i was including on my page
My best advice is to do what NickCoon had commented
echo $query;
to see the query that is being used. then strip all your page down to eliminate the issue

How do I manage multiple combined index keys in Yii MVC?

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.

Categories