Got three tables (blogs, tags, and blogtags) all AI and ID set to primary key. I'm making a tagging system to keep track of my sites (localhost). The code below is sort of working, but mysql_insert_id just doesn't seem reliable enough since I get some duplicate rows and the occasional 0 value in it.
/// inserts the blog into blog table.
$insert = mysql_query("INSERT INTO blogs (id, url, user, pass, dname, islocal, cat2post) VALUES ('', '$blog', '$bloguser', '$blogpassword', '','NO','$_POST[cat2blog]')")or die( 'Error: ' . mysql_error());
$taggit1 = mysql_insert_id();
$page->content .= "<p class=\"alert\">Success - External blog Added!</p>";
/// let's see what tags we have and explode them.
//$tags = $_POST['tags'] which is an array of words seperated by comma
$tags = 'fishing';
$pieces = explode(",", $tags);
/// go through the tags and add to tags table if needed.
foreach ($pieces as $l){
$l = trim($l);
$query = "SELECT id FROM tags WHERE tag = '$l'";
$result = mysql_query($query) or die( "Error: " . mysql_error() . " in query $query");
$row = mysql_fetch_array($result);
$taggit2 = $row[0];
if ($taggit2 == '') {
$insert2 = mysql_query("INSERT INTO tags (id, tag) VALUES ('','$l')")or die( 'Error: ' . mysql_error());
$taggit2 = mysql_insert_id();
$page->content .= "<p class=\"alert\">This tag didn't exist - so I inserted a new tag</p>";
}
/// for each tag we have, let's insert the blogstags table so we can reference which blog goes to which tag. Blogstags_id should map to the id of the blog.
$insert3 = mysql_query("INSERT INTO blogstags (id, tag_id, blogstags_id) VALUES ('','$taggit2','$taggit1')")or die( 'Error: ' . mysql_error());
}
Guess I need a different solution than mysql_insert_id - ideas? Suggestions?
As requested table structures:
CREATE TABLE IF NOT EXISTS `blogs` (
`id` int(11) NOT NULL auto_increment,
`url` text NOT NULL,
`user` text NOT NULL,
`pass` text NOT NULL,
`dname` text NOT NULL,
`islocal` varchar(3) NOT NULL,
`cat2post` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
CREATE TABLE IF NOT EXISTS `blogstags` (
`id` int(11) NOT NULL auto_increment,
`tag_id` int(11) NOT NULL,
`blogstags_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
CREATE TABLE IF NOT EXISTS `tags` (
`id` int(11) NOT NULL auto_increment,
`tag` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
mysql_insert_id() is working fine. The problem could be that you are using persistant connections. With persistant connections, all kinds of funky concurrency issues can happen. Don't use them unless you really, really have to.
Two options - you could switch to PostgreSQL which allows you to return an auto_incremented ID as part of the insert query.
Or, if you are sticking with MySQL, you can use the MySQL LAST_INSERT_ID() function -
Related
I have an php array:
$cont_array = Array("613:m-ent:id=one","930:m-lk:id=one;x=180;y=79;which=1","1080:m-lev:id=one;");
I want to insert it into a MySQL table with table-name as variable, like $table_name = "user1".
In addition, I want to break each array-element by the first ":" .After executing my php code I get just an empty table.
I need help please. This is my code:
<?php
$connection = mysqli_connect('localhost','root','','prueba');
$cont_array = Array("613:m-ent:id=one","930:m-clk:id=one;x=180;y=79;which=1","1080:m-lev:id=one;");
$table_name = "user1";
$sql_1 = "DROP TABLE IF EXISTS `".$table_name."`;";
$sql_1 .= "CREATE TABLE `".$table_name."` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`usercod` varchar(20) NOT NULL DEFAULT '',
`pid` varchar(1000) NOT NULL DEFAULT '',
`name` varchar(1000) NOT NULL DEFAULT '',
`time` varchar(1000) NOT NULL DEFAULT '',
`all_act` varchar(1000) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;";
mysqli_multi_query($connection,$sql_1);
foreach ($cont_array as $row){
$break_e = explode(':', $row, 2);
$sql="INSERT INTO`".$table_name."` (usercode,pid,name,time,all_act) VALUES ("user","pid_value","user_name",'$break_e [0]','$break_e [1]');";
mysqli_query($connection,$sql);
}
?>
This is what I get:
This is what I would like to get:
Your SQL seem to have issue check below SQL statement.
$sql = "INSERT INTO $table_name (usercod,pid,name,time,all_act) VALUES ('user','pid_value','user_name','".$break_e [0]."','".$break_e [1]."')";
I have made a user_login table, having pk = userid.
A credit_request table is created which references to userid as fk.
when the user login, he should see only his entries in the dashboard.
But, here i am not able to insert data, once i link a foreign key to it.
and even the data inserted through phpmyadmin is visible to all users.
Please help me out.
how to insert and retrieve data for logged in users.
<>
//Database setup for Credit request
//Insert data into Credit request
if(isset($_POST['taskid']))
{
$taskid =$_POST['taskid'];
$orderid = $_POST['orderid'];
$status = $_POST['status'];
$query1 = "INSERT INTO credit_request(taskid, orderid, status)
VALUES ('$taskid', '$orderid', '$status')";
if ($connect->query($query1) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query1 . "<br>" . $connect->error;
}
}
//Display data for credit request
$query2 = "SELECT taskid, orderid, status FROM credit_request WHERE agentid = '$userid'";
$res = $connect->query($query2);
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
echo "<br>taskid: " . $row["taskid"]. " -orderid: " . $row["orderid"]. " --:" . $row["status"]."";
}
} else {
echo "0 results";
}
I think you have problem on update, on delete when creating foreign key..
Here's an example of how you'd build your schema:
CREATE TABLE `country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE TABLE `state_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state_name` varchar(45) DEFAULT NULL,
`country_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `country_fk` FOREIGN KEY (`country_id`)
REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='';
INSERT INTO country (country_name) VALUES ('US of A');
INSERT INTO state_table (state_name,country_id) VALUES
('Minnesota', 2),
('Arizona', 2);
See this fiddle for more.
I am trying to read from a database in MySQL and insert my data in another database in MySQL .
my first table is like this
CREATE TABLE IF NOT EXISTS `link` (
`_id` bigint(20) NOT NULL AUTO_INCREMENT,
`country` varchar(30) COLLATE utf8 DEFAULT NULL,
`time` varchar(20) COLLATE utf8 DEFAULT NULL,
`link` varchar(100) COLLATE utf8 DEFAULT NULL,
PRIMARY KEY (`_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6149 ;
and the second table is
CREATE TABLE IF NOT EXISTS `country` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(15) CHARACTER SET utf8 NOT NULL,
`Logo` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Name_3` (`Name`),
UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8457 ;
There are about 6114 rows in first table that I'm trying to insert to second using this code
<?php
$tmp = mysqli_connect(******, *****, ****, *****); // First table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$main = mysqli_connect(*****, *****, ****, ******); //Second table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$req = "SELECT country FROM link";
$result = mysqli_query($tmp, $req) or die( mysqli_error($tmp) );
echo "-> ".mysqli_num_rows($result)."<br>";
while ($row = mysqli_fetch_array($result)) {
$con = $row["country"];
$req = "INSERT IGNORE INTO country (Name) VALUES ('$con')";
mysqli_query($main, $req) or die( mysqli_error($main) ) ;
}
?>
problem is the php code works but for 6114 take a very long time which I can't afford .
what is causing the code to take this long to work ? is it the "INSERT IGNORE" ?
is there any way I can do this faster ?
Since the databases are on the same server, you can simply use INSERT ... SELECT (which avoids having to bring the data into PHP and loop over the results executing separate database commands for each of them, so will be considerably faster):
INSERT INTO db2.country (Name) SELECT country FROM db1.link
you can try a create an index on column "country" of table Link.
I'm reading and store rss feed in my database ,my requirement is if link field is same then update title and description only in database.
I'm using ON DUPLICATE KEY UPDATE but after entered query.its insert only a single data in database and failed and show a error
my code is
<?php
include_once 'db.php';
$homepage = file_get_contents('http://rss.cnn.com/rss/edition_us.rss');
$movies = new SimpleXMLElement($homepage);
foreach($movies->channel->item as $opt){
$title= $opt->title;
$tittle=mysql_real_escape_string($title);
$link=$opt->link;
$links=mysql_real_escape_string($link);
$des=$opt->description;
$dess=mysql_real_escape_string($des);
"INSERT INTO store_feed (title, link, description) VALUES ('$tittle','$links','$dess')";
$sql="ON DUPLICATE KEY UPDATE title= '$tittle',description='$dess'";
$result=mysql_query($sql) or die( mysql_error() );
}
?>
and table structure is:-
CREATE TABLE `test_om`.`store_feed` (
`id` INT NOT NULL AUTO_INCREMENT ,
`title` VARCHAR( 200 ) NOT NULL ,
`link` VARCHAR( 200 ) NOT NULL ,
`description` VARCHAR( 500 ) NOT NULL ,
`feedburner` VARCHAR( 200 ) NOT NULL ,
PRIMARY KEY ( `id` ) ,
UNIQUE (
UNIQUE KEY `link` (`link`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
and error is
Duplicate entry 'http://rss.cnn.com/~r/rss/edition_us/~3/Wl1V4JsNqDU/index.html' for key 'link'
I have done some changes in my query ,short it.
<?php
include_once 'db.php';//config file
$homepage = file_get_contents('http://rss.cnn.com/rss/edition_us.rss');//link of rss feed page
$movies = new SimpleXMLElement($homepage);
foreach($movies->channel->item as $opt){
$sql="INSERT INTO store_feed SET `title` = '".mysql_real_escape_string($opt- >title)."',
`link`='".mysql_real_escape_string($opt->link)."',
`description`='".mysql_real_escape_string($opt->description)."'"
."ON DUPLICATE KEY UPDATE `title`='".mysql_real_escape_string($opt->title).
"',`description`='".mysql_real_escape_string($opt->description)."'";
$result=mysql_query($sql) or die( mysql_error() );
}
?>
and its solve my problem....
INSERT ... ON DUPLICATE has to be one query:
$sql="INSERT INTO store_feed (title, link, description) VALUES ('$tittle','$links','$dess')"
." ON DUPLICATE KEY UPDATE title= '$tittle',description='$dess'";
$result=mysql_query($sql) or die( mysql_error() );
You forgot to update the link field which causes the conflict.
i have a mysql database...
CREATE TABLE `applications` (
`id` int(11) NOT NULL auto_increment,
`jobref` int(11) NOT NULL,
`userid` int(11) NOT NULL,
`q1` text NOT NULL,
`q2` text NOT NULL,
`q3` text NOT NULL,
`sub_q1` text,
`sub_q2` text,
`sub_q3` text,
`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`printed` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `jobref` (`jobref`),
KEY `applications_ibfk_2` (`userid`),
CONSTRAINT `applications_ibfk_1` FOREIGN KEY (`jobref`) REFERENCES `jobs` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `applications_ibfk_2` FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='InnoDB free: 9216 kB; (`jobref`) REFER `iwcjobs/jobs`(`id`) '
and this php file, using mysqli for data operations.
<?php
require_once '../includes/constants.php';
if(isset($_POST['submit'])) {
$q1 = $_POST['question1'];
$q1a = $_POST['ifNoQuestion1'];
$q2 = $_POST['question2'];
$q2a = $_POST['ifNoQuestion2'];
$q3 = $_POST['question3'];
$q3a = $_POST['ifNoQuestion3'];
$JobRef = $_POST['jobref'];
$UserRef = $_POST['id'];
$mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was a problem connecting to the database');
if($stmt = $mysql->prepare('INSERT INTO `applications` VALUES (NULL,?,?,?,?,?,?,?,?,NULL,NULL)')) {
$stmt->bind_param('iissssss',$JobRef,$UserRef,$q1,$q2,$q3,$q1a,$q2a,$q3a);
$stmt->execute();
$stmt->close();
header('location: ../myApps.php?apr=y');
//echo ("<h2>success</h2> - $q1 . $q2 . $q3 . $q1a . $q2a . $q3a . $JobRef . $UserRef");
} else {
echo 'error: ' . $mysql->error;
}
} else {
echo 'errorStage2: ' . $mysql->error;
}
?>
The script is grabbing the correct values from the previous form, but not inserting them into the database. Any ideas people?
Thx in advance,
Aaron.
the way your insert query is currently written, you are trying to set id to NULL, which is a NOT NULL field.
it'd be better to structure the insert would be like this:
INSERT INTO 'applications' (jobref,userid,etc..) VALUES (?,?etc..)
this way, you not try to change id, and just let auto_increment do it's thing.