make a temporary table and select from it - php

I'm getting an error 'undeclared variable: temp' when I run this...
<?php
$maketemp = "CREATE TEMPORARY TABLE temp(`itineraryId` int NOT NULL, `live` varchar(1), `shipCode` varchar(10), `description` text, `duration` varchar(10), PRIMARY KEY(itineraryId))";
mysql_query( $maketemp, $connection ) or die ( "Sql error : " . mysql_error ( ) );
$inserttemp = "SELECT live, id AS itineraryId, ship AS shipCode, description AS description, duration AS length FROM cruises WHERE live ='Y' INTO temp";
mysql_query( $inserttemp, $connection ) or die ( "Sql error : " . mysql_error ( ) );
$select = "SELECT intineraryId, shipCode, description, duration FROM temp";
$export = mysql_query ( $select, $connection ) or die ( "Sql error : " . mysql_error( ) );
Any ideas ?

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
This code should work:
<?php
$maketemp = "
CREATE TEMPORARY TABLE temp_table_1 (
`itineraryId` int NOT NULL,
`live` varchar(1),
`shipCode` varchar(10),
`description` text,
`duration` varchar(10),
PRIMARY KEY(itineraryId)
)
";
mysql_query($maketemp, $connection) or die ("Sql error : ".mysql_error());
$inserttemp = "
INSERT INTO temp_table_1
(`itineraryId`, `live`, `shipCode`, `description`, `duration`)
SELECT `id`, `live`, `ship`, `description`, `duration`
FROM `cruises`
WHERE `live` = 'Y'
";
mysql_query($inserttemp, $connection) or die ("Sql error : ".mysql_error());
$select = "
SELECT `itineraryId`, `shipCode`, `description`, `duration`
FROM temp_table_1
";
$export = mysql_query($select, $connection) or die ("Sql error : ".mysql_error());
I guess you are going to do more stuff with the temporary table, or are just playing with it, but if not be aware that the whole code could be summed up with:
<?php
$query = "
SELECT `id` AS 'itineraryId', `ship`, `description`, `duration`
FROM `cruises`
WHERE `live` = 'Y'
";
$export = mysql_query($query, $connection) or die ("Sql error : ".mysql_error());

I like to use heredoc to help me construct embedded sql query (just to help make any subtle error glaring); so your first query would look something like this:
$maketemp =<<<s
CREATE TEMPORARY TABLE temp(
`itineraryId` int NOT NULL,
`live` varchar(1),
`shipCode` varchar(10),
`description` text,
`duration` varchar(10),
PRIMARY KEY(itineraryId));
s;
Then if you want to correct the 2nd query without listing the fields of the table you want to insert the records, you have to list the fields in the same order.
Just the query this time:
INSERT INTO temp
SELECT id, live, ship, description, duration
FROM cruises
WHERE live = 'y';
And last thing about temporary variable is this: Check out the part about its visibility.
You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed.
http://dev.mysql.com/doc/refman/5.5/en/create-table.html
What that means is this: when you're connected to MySQL directly, e.g. through a command line interface like this:
mysql> #our query here line-by-line
Then you're essentially on the same connection through all of your multiple queries as long as your session is active.
But in an external script (like PHP, for example), just because it's on the same script file doesn't necessarily mean it's the same connection so that by the time you execute your insert query, your temp table is not visible to that connection session.
Try to concat all the queries, send it all within a single command/query execution.
Good luck.

The second query is not correct.
From the reference -
MySQL Server doesn't support the SELECT ... INTO TABLE Sybase SQL
extension. Instead, MySQL Server supports the INSERT INTO ... SELECT.
standard SQL syntax, which is basically the same thing.
Try this one instead -
INSERT INTO temp
SELECT live
, id AS itineraryId
, ship AS shipCode
, description AS description
, duration AS length
FROM
cruises
WHERE
live = 'Y'

Related

Syntax error with SQL in PHP

I'm trying to set the column of a table to a string in every row if the column exists. However, I am receiving SQL syntax errors and can't pinpoint what exactly the issue is:
while($db = mysqli_fetch_array(mysqli_query($conn, "SHOW DATABASES"))){
$id = $db['id'];
$sql = /** #lang text */
"SELECT IF( EXISTS(
SELECT DISTINCT `info`
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('borrower')
AND TABLE_SCHEMA = '$db'))
BEGIN
UPDATE `info`
SET `borrower` = '****'
WHERE `id` = '$id'
END";
$query = mysqli_query($conn, $sql);
if (!$query){
// Deal with error
}
}
The syntax error I receive back:
information_schemadb1You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')BEGINUPDATE infoSET borrower = '****'' at line 5
I know it must be something very small but I have been stuck for a while and can't seem to find my error.
Try this syntax for the query-
IF EXISTS (SELECT DISTINCT `info`
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('borrower')
AND TABLE_SCHEMA = '$db')) THEN
UPDATE `info`
SET `borrower` = '****'
WHERE `id` = '$id'
END IF;
I added Then in the end of the if condition and End if instead of only if, and I removed the select to. What are you trying to select? it is only update clause.
update
Example from here
you can't use it like a normal query. Control structures like IF or
WHILE are only allowed in stored procedures or functions.
MYSQL panel
delimiter $$
create procedure YourIfConditionSP()
begin
IF EXISTS (SELECT DISTINCT `info`
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('borrower')
AND TABLE_SCHEMA = '$db') THEN
UPDATE `info`
SET `borrower` = '****'
WHERE `id` = '$id';
END IF;
end $$
delimiter ;
And you have to change your php code for calling the stored procedure.
PHP
//run the stored procedure
$result = mysqli_query($connection,
"CALL YourIfConditionSP") or die("Query fail: " . mysqli_error());
How to call a MySQL stored procedure from within PHP code?

Something mysterious with PHP, PDO (probably not MySQL) SQLSTATE[42000](1064)

Something really strange is happening with the following query, when I try it on PhpMyAdmin it works flawlessly, but when I run it from PHP I get the following error.
I'm using PDO...
Maybe I'm blind, or maybe it's the fact that I've been working for so many hours, the thing is that I don't see anything wrong.
Error message
SQLSTATE[42000]: Syntax error or access violation: 1064 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 downsync (id, signature) VALUES ('1','b01c0d494aca29162d815346d0de5f' at line 2
The query... Highlighted version (http://pastebin.com/dkYRJCS1)
CREATE TEMPORARY TABLE IF NOT EXISTS downsync (`id` int(11) NOT NULL, `signature` VARCHAR(250) NOT NULL);
INSERT INTO downsync (id, signature) VALUES ('1','b01c0d494aca29162d815346d0de5fd3'),
('2','bc3d25e2a527a20779914f5c7dc181e5'),
('3','89bc5c4e013aea0b28e61561ada05770'),
('4','8ce1daecd2a20c23b1c3344dac07880a'),
('6','0a679dc54c3654933329fc7bbf01c401'),
('7','40e6af407141ab652a4cad01f2f30a05'),
('9','331e12d5136a24483a12a0610f0ecd80'),
('10','570e68fd6cccd91aaf1173845739d9ab'),
('11','603e6a77d56a21597563119b319aaf67'),
('12','7649d3e71223cf543994189fe4053670'),
('14','825d0a186fd938eb0417a1bf3e30d9c3'),
('15','4a66d12f56b9ff93332b7c841c986751'),
('16','7de9d51199cdd316d869510fe97f584c'),
('17','7ef58d702ea43e02398f3f983c8292f3'),
('18','430c864532d3352691c76a9517f54498'),
('19','11a0e5cd2497166b0f85f3e318e6ff2f'),
('20','9771222ec70e55722e2582f3238f4e44'),
('21','bffd7ce7a4b59bb439a98ae898e3a703'),
('22','daf986c8682f856b1828cd4b1c8888b7'),
('23','3fecc9e7e6291b0ea12bbe60c46d361b'),
('24','41e49696971f00648f3a3e5971ea765d'),
('25','0f58aa0ffa8fd6efeb3bb4ccee590d44');
SELECT `downsync.id`,
IF(MD5(CONCAT(
customers.id,
IFNULL(customers.full_name,0),
IFNULL(customers.phone,0),
IFNULL(customers.mobile,0),
IFNULL(customers.email,0),
IFNULL(customers.address,0),
IFNULL(customers.zipcode,0),
IFNULL(customers.city,0),
IFNULL(customers.state,0),
IFNULL(customers.country,0),
IFNULL(customers.gmaps_addrs,0)
)) = signature,1,0) as unchanged
FROM downsync
INNER JOIN customers ON downsync.id = customers.id;
The Code...
"Here's the PHP source, I'm a little slow right now, sorry for forgetting it... ;)"
$query = "
CREATE TEMPORARY TABLE IF NOT EXISTS downsync (`id` int(11) NOT NULL, `signature` VARCHAR(250) NOT NULL);
INSERT INTO downsync (id, signature) VALUES ('1','b01c0d494aca29162d815346d0de5fd3'),
('2','bc3d25e2a527a20779914f5c7dc181e5'),
('3','89bc5c4e013aea0b28e61561ada05770'),
('4','8ce1daecd2a20c23b1c3344dac07880a'),
('6','0a679dc54c3654933329fc7bbf01c401'),
('7','40e6af407141ab652a4cad01f2f30a05'),
('9','331e12d5136a24483a12a0610f0ecd80'),
('10','570e68fd6cccd91aaf1173845739d9ab'),
('11','603e6a77d56a21597563119b319aaf67'),
('12','7649d3e71223cf543994189fe4053670'),
('14','825d0a186fd938eb0417a1bf3e30d9c3'),
('15','4a66d12f56b9ff93332b7c841c986751'),
('16','7de9d51199cdd316d869510fe97f584c'),
('17','7ef58d702ea43e02398f3f983c8292f3'),
('18','430c864532d3352691c76a9517f54498'),
('19','11a0e5cd2497166b0f85f3e318e6ff2f'),
('20','9771222ec70e55722e2582f3238f4e44'),
('21','bffd7ce7a4b59bb439a98ae898e3a703'),
('22','daf986c8682f856b1828cd4b1c8888b7'),
('23','3fecc9e7e6291b0ea12bbe60c46d361b'),
('24','41e49696971f00648f3a3e5971ea765d'),
('25','0f58aa0ffa8fd6efeb3bb4ccee590d44');
SELECT `downsync.id`,
IF(MD5(CONCAT(
customer.id,
IFNULL(customer.name,0),
IFNULL(customer.email,0),
IFNULL(customer.gmaps_addrs,0)
)) = signature,1,0) as unchanged
FROM downsync
INNER JOIN commerces ON downsync.id = commerces.id;
";
echo '<pre>';var_dump($query);echo '</pre>';
try {
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->query($query);
//> I tried to commet this and use the query method but it didn't work
//$stmt->setFetchMode(PDO::FETCH_ASSOC);
//$stmt->execute($params);
$results = $stmt->fetchAll();
}
catch(Exception $e) {
echo 'Exeption:<pre>';var_dump($e->getMessage());echo '</pre><hr>';
echo 'Error Obj.: <pre>';var_dump($e);echo '</pre>';
}
Solution:
Separating the 3 queries did the trick
$query1 = 'CREATE TEMPORARY TABLE IF NOT EXISTS....';
$query2 = 'INSERT INTO downsync...';
$query3 = 'SELECT downsync.id...';
...
$stmt = $pdo->query($query);
$stmt = $pdo->query($query2);
$stmt = $pdo->query($query3);
Thanks #lafor, #Prava - Mindfire Solutions, #Ravinder

data's cannot be inserted

I have database contain table named demnads
table contain 11 cell first one is id auto increasement
I want to add data's with this sql command in php :
<?php
$hostname_mystore = "localhost";
$database_mystore = "mystore";
$username_mystore = "root";
$password_mystore = "";
$mystore = mysql_pconnect($hostname_mystore, $username_mystore, $password_mystore) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_query("set character_set_server='utf8'");
mysql_query("set names 'utf8'");
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql= "INSERT into demands ( itemname , case , cname , fatora , client , cdate , ctime , prices , cmobile , numbers) values('$item[$i]','$cases[$i]','$customer[$i]','$fatora[$i]','$client[$i]','$dates[$i]','$times[$i]','$price[$i]','$mobile[$i]','$numbers[$i]' )";
?>
but data's didn't be inserted
You have switched from the mysql library (which is deprecated) to mysqli:
mysqli_connect_errno()
You should use one or the other.
Also, embedded array values need to be enclosed in curly brackets{$item[$i]}.
This assumes, of course, that these arrays and $i are defined elsewhere.
And you haven't shown the statement that actually inserts the data.
You forgot to call mysql_query( $sql, $conn )
Enclose your column names with backticks. case is a keyword within MySQL and as such can not be used as a column name without the backticks!
$sql= "INSERT into demands ( `itemname` , `case` , `cname` , `fatora` , `client` , `cdate` , `ctime` , `prices` , `cmobile` , `numbers`) values('$item[$i]','$cases[$i]','$customer[$i]','$fatora[$i]','$client[$i]','$dates[$i]','$times[$i]','$price[$i]','$mobile[$i]','$numbers[$i]' )";
You said your table name is demnads . But in Coding you used demands?
Check again.

PHP + MySQL is complicated

I am using XMAPP and MySQL is running as it should. In phpMyAdmin, I don't really get the point so I tried creating one in PHP. With this code it tells me the database benutzer. benutzer doesn't exists although I created one in phpMyAdmin and in this code:
<?php
$connect = mysql_connect("127.0.0.1","root","") or die ("Alles scheisse!");
$db = mysql_select_db("benutzer") or die ("Keine benutzer!");
$sql = "CREATE TABLE 'benutzer'
id VARCHAR(100),
name VARCHAR(100),
mail VARCHAR(100),
points INT(1000)
)";
$sql = "INSERT INTO benutzer(`id` , `name` , `mail` , `points`)VALUES(NULL , 'Liam', 'liam#mail.com', '100');";
$db_erg = mysql_query($sql)
or die("Anfrage fehlgeschlagen: " . mysql_error());
?>
Have you also created a table "benutzer" inside db "benutzer"? Your code does not execute your first SQL statement "CREATE TABLE.." so there will be no table "benutzer" if you don't have one created in phpmyadmin.
Did you created the database under the root user? Because you are connecting to the root in your code.

Insert into two tables from a single form

Insert into two tables from a single form. The first insert go in fine the second generates this error Duplicate entry '0' for key 1 any idea what is happening?
$connection=mysql_connect ("localhost", "foo", "bar") or die ("I cannot connect to the database.");
$db=mysql_select_db ("database", $connection) or die (mysql_error());
$query = "INSERT INTO worklog (id, newtime, datetime, clientname, clientcode, startmo, startday, startyr, endmo, endday, endyr, duemo, dueday, dueyr, market, job, allTypes, spec, status, designer, dsgnemail, adrep, ademail, frame1, frame2, frame3, rush) VALUES ('$id', $newtime, now(), '$clientname', '$clientcode', '$startmo', '$startday', '$startyr', '$endmo', '$endday', '$endyr', '$duemo', '$dueday', '$dueyr', '$market', '$job', '$allTypes', '$spec', '$status', '$designer', '$dsgnemail', '$adrep', '$ademail', '$frame1', '$frame2', '$frame3', '$rush')";
$sql_result = mysql_query($query, $connection) or die (mysql_error());
$worklog_id=mysql_insert_id($connection);
$connection2=mysql_connect ("localhost", "foo", "bar") or die ("I cannot connect to the database.");
$db2=mysql_select_db ("database", $connection2) or die (mysql_error());
$query2 = "INSERT INTO worklognotes (worklog_id, spec) VALUES ('$worklog_id', '$spec')";
$sql_result = mysql_query($query2, $connection2) or die (mysql_error());
I thin the culprit is the line:
$worklog_id=mysql_insert_id($connection);
according to the PHP documentation:
"The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established"
So if the id in worklog is not AUTO_INCREMENT it will always return 0 ... your second attempt at running the code will cause:
Duplicate entry '0' for key 1
Two ways to fix this:
id for worklog should be AUTO_INCREMENT ... this way mysql_insert_id will return ther ID generated by the database and you can use it as a working id for the next query
just use $id instead of $worklog_id
normally with and table ID column you set it to auto-increment and never explicitly insert it. The database management system will take care of inserting that column. The error means that you are inserting a row that has that ID already, meaning the column has a UNIQUE constraint.

Categories