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.
Related
I want Data insert into mysql using PHP. I am writing script HTML, PHP and I create Mysql database. I don't understand data not send mysql server. Here is the HTML and PHP code:
<?php
if (isset($_POST['submit'])){
$con = mysql_connect("localhost","root","");
if(!$con){
die("Can not connect: " . mysql_error());
}
//Database Connection.
mysql_select_db("learnarabic",$con);
$sql = "INSERT INTO article(ArticleDate,ArticleAuthor,ArticleSubject,ArticleSource,ArticleLevel,ArticleTitleEnglish,ArticleTitleArabic,ArticleFree,ArticleEnglish,ArticleTranslationEnglish,ArticleArabic,ArticleVowels,ArticleTransliteration,ArticleAudio)
VALUES
('$_POST['ArticleDate']',
'$_POST['ArticleAuthor']',
'$_POST['ArticleSubject']',
'$_POST['ArticleSource']',
'$_POST['ArticleLevel']',
'$_POST['ArticleTitleEnglish']',
'$_POST['ArticleTitleArabic']',
'$_POST['ArticleFree']',
'$_POST['ArticleEnglish']',
'$_POST['ArticleTranslationEnglish']',
'$_POST['ArticleVowels']',
'$_POST['ArticleTransliteration']',
'$_POST['ArticleAudio']',
'$_POST['ArticleArabic']')";//Insert data into Mysql.
mysql_query($sql,$con);
mysql_close($con);//Connection Close.
}
?>
Here is the SQL Database code:
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `learnarabic`
--
-- --------------------------------------------------------
--
-- Table structure for table `article`
--
CREATE TABLE IF NOT EXISTS `article` (
`articleid` int(250) NOT NULL AUTO_INCREMENT,
`ArticleDate` date NOT NULL,
`ArticleAuthor` varchar(250) NOT NULL,
`ArticleSubject` varchar(250) NOT NULL,
`ArticleSource` varchar(250) NOT NULL,
`ArticleLevel` varchar(250) NOT NULL,
`ArticleTitleEnglish` varchar(250) NOT NULL,
`ArticleTitleArabic` varchar(250) NOT NULL,
`ArticleFree` varchar(250) NOT NULL,
`ArticleEnglish` longtext NOT NULL,
`ArticleTranslationEnglish` longtext NOT NULL,
`ArticleArabic` longtext NOT NULL,
`ArticleVowels` longtext NOT NULL,
`ArticleTransliteration` longtext NOT NULL,
`ArticleAudio` blob NOT NULL,
PRIMARY KEY (`articleid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
I need a solution.
Try removing the $con variable from the mysql_query() function eg mysql_query($sql); also add single quotes to any text inside $_POST like $_POST['something']
I restarted the MySQL service and I attempted to use my PHP programs delete function to delete an existing row but I'm finding although the delete queries were counted the row was not deleted. I tried applying on delete cascade to the foreign key of the child table but that did not seem to have an effect. I'm wondering why the delete would be doing nothing.
CREATE TABLE `customers` (
`idcustomers` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(45) DEFAULT NULL,
`lastname` varchar(45) DEFAULT NULL,
`address1` varchar(45) DEFAULT NULL,
`address2` varchar(45) DEFAULT NULL,
`city` varchar(45) DEFAULT NULL,
`state` varchar(45) DEFAULT NULL,
`zip` varchar(45) DEFAULT NULL,
`phone` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`cell` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idcustomers`),
UNIQUE KEY `idcustomers_UNIQUE` (`idcustomers`)
) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=latin1
CREATE TABLE `events` (
`idevents` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(250) DEFAULT NULL,
`start` datetime DEFAULT NULL,
`end` datetime DEFAULT NULL,
`allday` varchar(50) DEFAULT NULL,
`url` varchar(1000) DEFAULT NULL,
`customerid` int(11) NOT NULL,
`memo` longtext,
`dispatchstatus` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idevents`),
KEY `FK_events` (`customerid`),
CONSTRAINT `FK_events` FOREIGN KEY (`customerid`) REFERENCES `customers` (`idcustomers`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1
Com_delete 2
The PHP looks like this:
<?php
session_start();
date_default_timezone_set("America/Los_Angeles");
if($_SESSION['loggedin'] != TRUE)
{
header("Location: index.php");
}
require_once('../php.securelogin/include.securelogin.php');
$mysqli = new mysqli($ad_host, $ad_user, $ad_password, "samedaycrm");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$customerid = $_SESSION['customer_id'];
$tSQL = "delete from events where customerid = \"$customerid\"";
$result = $mysqli->query($tSQL);
$tSQL = "delete from customers where idcustomers = \"$customerid\"";
$result = $mysqli->query($tSQL);
echo $mysqli->error;
?>
Assuming that the customerid and idcustomers columns are both numeric it should be fine. You should not need to quote the variables in those queries btw, then you wouldnt need to escape them. You may try:
$tSQL = "delete from events where customerid = $customerid";
but it should not be any different than what you used already. Of course if you are not sure of the type of the column you can use:
$tSQL = "delete from events where customerid = '".$customerid."'";
or you can get away with:
$tSQL = "delete from events where customerid = '$customerid'";
but I have always hated that for some reason.
if all of that fails troubleshoot by spitting out the $customerid (or even the whole $tSQL) variable and then trying the query manually in phpmyadmin or toad or whatever db client you use, and see what it tells you. If it just says 0 rows affected, then run it like a select instead. Tailor to fit.
I am new to php and SQL so this is probably an easy question but I could not find any good sources online.
I am trying to create a SQL table when someone submits a form and this is what I have so far
include("dbstufflive.php");
$cxn = mysqli_connect($host,$user,$passwd,$dbname)
or die("Couldn't connect to server");
$sql = "CREATE TABLE IF NOT EXISTS `$company` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`company_name` varchar(80) NOT NULL,
`contact` varchar(50) NOT NULL,
`email` varchar(80) NOT NULL,
`phone` varchar(13) NOT NULL,
... (long list of table data)
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ";
mysqli_query($cxn,$sql);
I will of course be doing other stuff with this table but I think I have most of that under control.
The problem is that this statement does not actually create my table :( The SQL statement works in phpadmin when I enter it as is and also there are no errors when the script runs. So it goes through all of this, and more, and seems to work but the table simply doesn't appear.
I can supply more code if needed but I don't want to paste more code here than is necessary.
Thanks in advance for any help from the community.
EDIT:
I was using wrong DBinfo...wow, I am not very bright.
Your SQL Statement looks fine - from the looks of it, you are missing your login credentials. An efficient way to do so:
// Add this line
require_once('config.php');
// Then change the variables below to pull your credentials from that file.
$cxn = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD)
or die("Couldn't connect to server");
$sql = "CREATE TABLE IF NOT EXISTS `$company` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`company_name` varchar(80) NOT NULL,
`contact` varchar(50) NOT NULL,
`email` varchar(80) NOT NULL,
`phone` varchar(13) NOT NULL,
... (long list of table data)
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ";
mysqli_query($cxn,$sql);
Then create a new file called config.php in same directory. Put your credentials:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASSWORD', 'your_password');
define('DB_DATABASE', 'database_name');
?>
You should check the result of mysqli_query (as far as i know it returns false on failure). See mysqli documentation for details, where you can read, that "Create table doesn't return a resultset" but True/false on sucess/failure.
example:
if (!mysqli->query($cxn,$sql)) {
printf("Error: %s\n", mysqli_error($cxn));
}
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 -
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.