I am trying to post data into two databases namely add_product and ledger but I keep getting the following error message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, amount)values('mnbvx', 'opening stock', '5')' at line 1
Below is my PHP code:
<?php
include ('session.php');
if($_GET["name"] && $_GET["opening"]&& $_GET["re"])
{
$servername="localhost";
$username="root";
$db="multiple";
$pass="";
mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$name=$_GET["name"];
$op=$_GET["opening"];
$re=$_GET["re"];
mysql_query("insert into add_product (product, opening, current, reorder)values('$name', '$op', '$op', '$re')");
mysql_query("insert into ledger (product, desc, amount)values('$name', 'opening stock', '$op')")or die(mysql_error());
print "<h4>product added to database</h4>";
print "<p><a href='add_pdt.html'>add another?</a></p>";
print "<a href='index_admin.php'>home</a>";
}
else{
print "please fill all fields correctly";
print " ";
print "<p><a href='add_pdt.html'>back</a></p>";
print "<p><a href='index_admin.php'>home</a></p>";
}
?>
below is - Table structure for table `ledger`
CREATE TABLE IF NOT EXISTS `ledger` (
`product` varchar(60) NOT NULL,
`desc` varchar(60) NOT NULL,
`amount` varchar(15) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
below --
-- Table structure for table `add_product`
CREATE TABLE IF NOT EXISTS `add_product` (
`product` varchar(30) NOT NULL,
`id` int(30) NOT NULL,
`opening` int(100) NOT NULL,
`current` int(100) NOT NULL,
`reorder` int(6) NOT NULL,
`updateon` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=93 ;
--
Use this query instead of your second query.
mysql_query("insert into ledger (`product`, `desc`, `amount`)values('$name', 'opening stock', '$op')")or die(mysql_error());
DESC is a reserved keyword. Either use backticks around it:
`desc`
or rename it.
desc is resevered ... and mysql is depricated...
use
$con = ('localhoat','root','','database_name');
mysqli_query($con,"insert into ledger (`product`, `desc`, `amount`)values('$name','opening stock', '$op')")or die(mysql_error()");
Related
The mysql query below gets me the results I need. The Trouble im having is creating it in php. Im trying to create the two temp tables below from two sets of date range forms then join the results of the temporary tables to display my final result. The dates in the where clauses are where I will use the form fields. The query below works great in mysql. Wondering if anyone can give me a fresh perspective on how i can approach this. Thanks
CREATE TEMPORARY TABLE upsfsttable
SELECT custname,custno,sm,dhlfrt,franchise,date,sublob,resets
FROM upsfreightfstimport
WHERE date > '2014-02-01' and date < '2014-02-28';
CREATE TEMPORARY TABLE sublobrange
SELECT customername,customerno,lob,franchisename,invoicedate,salesrep,items,retail,cost,margin,lineofbiz
FROM sublob2014
WHERE invoicedate > '2014-04-01' and invoicedate < '2014-04-30';
SELECT upsfsttable.custname,upsfsttable.custno,upsfsttable.date,sublobrange.customername,
sublobrange.customerno,sublobrange.invoicedate,sublobrange.items,sublobrange.retail,sublobrange.cost,sublobrange.margin,sublobrange.lineofbiz
FROM upsfsttable
JOIN sublobrange ON upsfsttable.custno = sublobrange.customerno and upsfsttable.dhlfrt = sublobrange.lineofbiz;
<?php
//make first temptable
$maketemp1 = "
CREATE TEMPORARY TABLE `upsfsttable` (
`fusfstId` int(11) NOT NULL,
`custname` varchar(200) DEFAULT NULL,
`custno` varchar(50) DEFAULT NULL,
`sm` varchar(11) DEFAULT NULL,
`dhlfrt` varchar(11) DEFAULT NULL,
`franchise` varchar(100) DEFAULT NULL,
`date` date DEFAULT NULL,
`sublob` varchar(25) DEFAULT NULL,
`resets` varchar(25) DEFAULT NULL
)
";
mysql_query($maketemp1, $dbhandle) or die ("Sql error : ".mysql_error());
//make second temptable
$maketemp2 = "
CREATE TEMPORARY TABLE `sublobrange` (
`slid` int(11) NOT NULL,
`customername` varchar(200) DEFAULT NULL,
`customerno` varchar(50) DEFAULT NULL,
`lob` varchar(11) DEFAULT NULL,
`franchisename` varchar(100) DEFAULT NULL,
`invoicedate` date DEFAULT NULL,
`salesrep` varchar(100) DEFAULT NULL,
`items` decimal(18,0) DEFAULT NULL,
`cost` decimal(18,2) DEFAULT NULL,
`retail` decimal(18,2) DEFAULT NULL,
`margin` decimal(18,2) DEFAULT NULL,
`lineofbiz` varchar(25) DEFAULT NULL
)
";
mysql_query($maketemp2, $dbhandle) or die ("Sql error : ".mysql_error());
//insert into first temptable
$inserttemp1 = "
INSERT INTO upsfsttable
(`custname`, `custno`, `sm`, `dhlfrt`, `franchise`,`date`,`sublob`,`resets`)
SELECT `custname`, `custno`, `sm`, `dhlfrt`, `franchise`, `date`, `sublob`, `resets`
FROM `upsfreightfstimport`
WHERE `date` BETWEEN '2014-02-01' AND '2014-02-28'
";
mysql_query($inserttemp1, $dbhandle) or die ("Sql error : ".mysql_error());
//insert into second temptable
$inserttemp2 = "
INSERT INTO sublobrange
(customername, customerno, lob, franchisename, invoicedate,salesrep,items,cost,retail,margin)
SELECT customername, customerno, lob, franchisename, invoicedate,salesrep,items,cost,retail,margin
FROM sublobrange
WHERE date BETWEEN '2014-04-01' AND '2014-04-30'
";
mysql_query($inserttemp2, $dbhandle) or die ("Sql error : ".mysql_error());
?>
";
}
//close the connection
mysql_close($dbhandle);
?>
My 3 tables namely product, band, product Info
Product
CREATE TABLE IF NOT EXISTS `product` (
`p_id` int(11) NOT NULL AUTO_INCREMENT,
`product` varchar(50) NOT NULL,
PRIMARY KEY (`p_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `product` (`p_id`, `product`) VALUES
(1, 'Atta'),
(2, 'OIl');
Brand
CREATE TABLE IF NOT EXISTS `brand` (
`b_id` int(11) NOT NULL AUTO_INCREMENT,
`p_id` int(11) NOT NULL,
`brand` varchar(50) NOT NULL,
`image` varchar(255) NOT NULL,
PRIMARY KEY (`b_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
Insert
INSERT INTO `brand` (`b_id`, `p_id`, `brand`, `image`) VALUES
(1, 1, 'Ashirvad', 'FreeVector-Blue-Squares-Vector.jpg'),
(2, 1, 'Phillsberry', 'ILBAGNOALESSI_One_02.jpg'),
(3, 2, 'Sunflower', '001-bi-fold-corporate-brochure-template-vol-1-2.jpg');
Product Info
CREATE TABLE IF NOT EXISTS `product_info` (
`pi_id` int(11) NOT NULL AUTO_INCREMENT,
`pro` int(11) NOT NULL,
`b_id` int(11) NOT NULL,
`quantity` varchar(20) NOT NULL,
`measurement` varchar(20) NOT NULL,
`mrp` varchar(20) NOT NULL,
`our_price` varchar(20) NOT NULL,
PRIMARY KEY (`pi_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
Insert
INSERT INTO `product_info` (`pi_id`, `pro`, `b_id`, `quantity`, `measurement`, `mrp`, `our_price`) VALUES
(1, 1, 1, '1', 'kg', '50', '48'),
(2, 1, 2, '1', 'kg', '60', '59'),
(3, 2, 3, '1', 'ltr', '90', '86');
When i use the below query to display data according to the p_id, it displays data correctly
<?php
// Make a MySQL Connection
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not Connect to DB :'. mysql_error());
}
mysql_select_db("mr_bazaar",$con);
$result = mysql_query("select * FROM product");
echo '<ul class="list-1 p2">';
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo '<li>';
echo "<a href='page1.php?$row[p_id]'>";
echo '<b>';
echo $row['product'];
echo '</b>';
echo "</a>";
echo '</li>';
}
echo '</ul>';
mysql_close($con);
?>
and I want to display data according to the p_id in another page page1.php using the table product, brand, product_info(product from product table),(brand from brand table), (quantity, mrp from product_info table)
Send the product id to the next page as a URL parameter. So change,
echo "<a href='page1.php?$row[p_id]'>";
to
echo "<a href='page1.php?pid=$row[p_id]'>";
and accept the pid in page1.php using
$pid=$_GET['pid']; // getting the URL parameter
Now you can query to get the details corresponding to the pid.
mysql_query("SELECT p.product,b.brand,pi.quantity,pi.mrp FROM product as p INNER JOIN brand as b ON p.p_id=b.p_id
INNER JOIN product_info as pi ON pi.b_id=b.b_id WHERE p.p_id=$pid");
1- For sending the product id to page1.php, pass the variable correctly, change
echo "<a href='page1.php?$row[p_id]'>";
to
echo "<a href='page1.php?pid=$row[p_id]'>";
2- Get the variable on page1.php using:
$pid = $_GET['pid'];
3- Query the database for record of that product
$result = mysql_query("select * FROM product WHERE p_id='{$pid}'");
*Note:
1- I would recommend you not to use mysql_* function use mysqli or pdo library instead, and also escape the string while getting it from GET parameter.
2- You can use joins to fetch data from other tables corresponding to current product
my SQL statement is not outputting anything when run. Just an empty screen.
Here is my PHP code:
<?php
$con = mysqli_connect("localhost", "root", "root","payBills");
$paidBills = "SELECT * FROM houseBills WHERE houseID = '20'";
$resultset = mysqli_query($con, $paidBills);
$records = array();
//Loop through all our records and add them to our array
while ($r = mysqli_fetch_assoc($resultset)) {
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
?>
and here is my SQL tables
CREATE TABLE `houseBills` (
`houseBillID` int(11) NOT NULL AUTO_INCREMENT,
`houseID` varchar(11) NOT NULL,
`name` varchar(50) NOT NULL,
`amount` varchar(10) NOT NULL,
`date` varchar(50) NOT NULL,
`addedBy` varchar(100) NOT NULL,
PRIMARY KEY (`houseBillID`),
UNIQUE KEY `houseBillID` (`houseBillID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `houseBills`
--
INSERT INTO `houseBills` (`houseBillID`, `houseID`, `name`, `amount`, `date`, `addedBy`) VALUES
(1, '20', 'Loo roll', '£10', '10', 'samstone920#googlemail.com'),
(2, '20', 'toothpaste', '3', 'egreg', '44tq');
Is there any plainly obvious that I am missing?
Table is currently set as CHARSET=latin1 JSON_ENCODE doesn't except this. See this post: json_encode is returning NULL?. ALTER TABLE houseBills CONVERT TO CHARACTER SET utf8;
Because the table already contains data before the alteration this stills give a problem. In this case (test phase project) the solution is to re-enter data. For large existing table perhaps try copying data to new table might offer a solution. Please note this is untested.
<?php
$ll=mysql_query("CREATE TABLE IF NOT EXISTS p (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`colum` varchar(255) NOT NULL DEFAULT '',
`ord` varchar(255) NOT NULL DEFAULT '',
`tex` varchar(255) NOT NULL DEFAULT '',
`search` varchar(255) NOT NULL DEFAULT '',
`count` varchar(255) NOT NULL DEFAULT '',
`order` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g');") or die(mysql_error()) ;
if($ll){
echo "insert AND CREATE ";}
else {echo "fail"; }
?>
I am working in a php language . In this page if the table is not created 1st create it and then insert the values into the column
After creating the table , I am inserting the values into the table but it showing me the error in the insert query
I am getting a this error- You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO p VALUES ('count','name','asc','1','search','count','order ')' at line 11
what am i doing wrong
I am not absolutly sure if that is the problem but you are passing 7 values in your INSERT statement while your table deffinition has 8 fields.
I assume you are doing that because 'id' field is autoincremental. However, if that is the case, you should specify which columns correspond with your values in the insert statement:
INSERT INTO $p (title, column, ord, ...) VALUES ('$a','$b','$c','$d','$f','$h','$g')
Here is a dry run seperating the two statements - should work:
<?php
$querys[]="CREATE TABLE IF NOT EXISTS $p (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`colum` varchar(255) NOT NULL DEFAULT '',
`ord` varchar(255) NOT NULL DEFAULT '',
`tex` varchar(255) NOT NULL DEFAULT '',
`search` varchar(255) NOT NULL DEFAULT '',
`count` varchar(255) NOT NULL DEFAULT '',
`order` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1";
$querys[]="INSERT INTO $p VALUES (null,'$a','{$b}','{$c}','{$d}','{$f}','{$h}','{$g}')";
foreach($querys as $sql) {
$ll = mysql_query($sql);
$error=mysql_error();
if($error!='') {
print $sql."\n";
die($error);
}
}
?>
INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g')
should be
INSERT INTO p (`title`,`colum`,`ord`,`tex`,`search`,`count`,`order`) VALUES ('$a','$b','$c','$d','$f','$h','$g')
Hence order is a mysql keyword
you have ended the insert statement with a " double quote but not started you can write either
INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g');
or you can write
("INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g')");
try it in your code
note - please do not use mysqli and mysql in same code, rather you can use mysqli PDO
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.