SQLite error on table creation with index - php

I am trying to make SQLite3 database with PHP that has an index.
There is an example on dev.mysql that makes an index like the one below.
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE sales (
kitchen_name VARCHAR(255) NOT NULL,
amount_name VARCHAR(255),
amount NUMERIC(15,2),
name_key VARCHAR(255) NOT NULL,
flag_total TINYINT(1),
INDEX kitchen_value_key (kitchen_name,name_key)
);");
I have run the query in an online parser and it is coming back as valid MySQL.
But I keep getting the error:
SQLite3::exec(): near "INDEX": syntax error
What am I doing wrong?

This is indeed valid MySQL syntax, but you aren't using MySQL, you're using SQLite, which is a different RDBMS.
SQLite just doesn't support the syntax for inlining index definitions in the table definitions, so you'll have to resort to using two separate statements:
CREATE TABLE sales (
kitchen_name VARCHAR(255) NOT NULL,
amount_name VARCHAR(255),
amount NUMERIC(15,2),
name_key VARCHAR(255) NOT NULL,
flag_total TINYINT(1)
);
CREATE INDEX kitchen_value_key ON sales(kitchen_name,name_key);
SQLFiddle

SQLITE is not mysql. They have very different syntactic rules at points
I'm assuming you want to create a normal index on the SQLITE table.
Put the index creation in a seperate statement from the table creation.
You should follow the instructions on
https://www.sqlite.org/lang_createindex.html
CREATE INDEX IF NOT EXISTS kitchen_value_key ON sales (kitchen_name, name_key)

Related

mysql 1064 error SYNTAX ERROR

I keep getting this error every time i try to create a table in my sql database:
Error in query (1064): Syntax error near 'CREATE TABLE IF NOT EXISTS users ( id int(10) NOT NULL AUTO_INCREMENT, `' at line 2
Could I get some help with this?
use luke_f_db
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`trn_date` datetime NOT NULL,
PRIMARY KEY (`id`)
);
There's an error with your use command. Add an ; behind the first line or just check if the database exists and your account has access to it.
The CREATE Code worked fine for me.
You could run only one command per query**. The mySQL command line client allows you to split multiple commands with ; but still runs them sequentially.
Remove the use luke_f_db line. The database to be used should be selected within the connect command. See http://www.w3schools.com/php/func_mysqli_connect.asp:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
The database name is the last argument to mysqli_connect.
The same information is found in the official PHP documentation: http://php.net/manual/en/mysqli.construct.php
** Some mySQL client implementations also allow multiple commands in one call, but you should avoid it. Using this feature in a script isn't portable to other databases and you won't ever know which of your commands triggered an error if one occurs.

How to autosend email to user when new product is added to database?

I have table 'emails' and row 'kategorija' where are stored values(they are in table 'proizvodi' in row 'kategorija') from checkboxes.
In row 'email' are stored emails from users, and users can check checkboxes(values in table 'proizvodi', row 'kategorija'), checked values are stored in table 'emails' in row 'kategorija'.
When new product(it has values like 'alati, satovi and others') is added to database, I need somehow autosend email with information that new product is available in 'kategorija', which has user selected in checkboxes, to users adress stored in table 'emails'.
Table 'emails':
CREATE TABLE IF NOT EXISTS `emails` (
`id` int(15) NOT NULL,
`email` varchar(255) CHARACTER SET utf8 COLLATE utf8_croatian_ci NOT NULL,
`kategorija` varchar(255) COLLATE utf8_bin NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
Table 'proizvodi' :
CREATE TABLE IF NOT EXISTS `proizvodi` (
`id` int(11) NOT NULL,
`naziv` varchar(55) CHARACTER SET utf8 DEFAULT NULL,
`cijena` decimal(8,2) DEFAULT NULL,
`slika` text CHARACTER SET utf8,
`opis` text CHARACTER SET utf8,
`kategorija` enum('alati','glazbeni_instrumenti','smartphone','laptop','fotoaparat_kamera','tehnicka_roba_ostalo','sportska_oprema','satovi','kucanski_aparati','ostalo_ostalo') CHARACTER SET utf8 DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=196 DEFAULT CHARSET=latin1;
I might not understand the question properly. I think it is quite simple:
When you insert the new product, retrieve its product id and category.
Then select email from emails where kategorija where categoria like '%%' to get the emails to use.
Finally iterate over those email addresses and send out the emails with your favorite email lib in your favorite language.
You might have find a better solution to store multiple categories for the emails, now I can see that you're using a plain string. It is not totally rocket proof, you shall rather use an n:n relation between a (yet to define) category table and the email table, and use the (yet to define) category table as a foreign key instead of using a hardcoded enum in the table definition of products for categories. Having a dedicated category table allows you to add further categories at any time without changing any code or table structure.
I (although I am not a native English speaker either) found a very good idea to use plain English terms for table names, column names, as well as variables, etc. This allows you to involve later on other developers.
Some other databases, for example Oracle has a built-in procedural language which allows you sending an email right from the database. Combining that with a database trigger when a new product is inserted, you can have this whole functionality implemented in about 10 lines of PL/SQL code.
I found that Oracle well worth of its price, and if you can't afford that, Oracle XE is available at free of charge. With the built-in PL/SQL language and lots of built-in packages, it makes database oriented application development a snap. This offers two magnitude faster speed than e.g. Hibernate plus MySQL in a heavy I/O transactional application.
Sorry, it is not possible to achieve your goal in MySQL. See https://stackoverflow.com/questions/31667462/how-to-send-an-email-from-mysql-using-a-stored-procedure for the reasons.
A possible workaround by making the database outputting emails into files, which is then processed by another application is described here: How to send email from MySQL 5.1
Another workaround is to create a custom UDF which can be called from your trigger on the product table. User-defined functions (UDF) allow you to call external code from your database, this way you can implement whatever feature you need.
If you could use Oracle, the built-in UTL_MAIL package allows you sending email directly from the database, for example from a trigger on the product table.
An example of sending an email is here: http://www.orafaq.com/wiki/Send_mail_from_PL/SQL
I have created new table 'obavijest'.
CREATE TABLE IF NOT EXISTS `obavijest` (
`id` int(10) unsigned NOT NULL,
`email` varchar(255) COLLATE utf8_bin NOT NULL,
`kategorija` varchar(255) COLLATE utf8_bin NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
On table 'emails' I created trigger to auto send values to table obavijest.
CREATE TRIGGER `obavijesttrig` AFTER INSERT ON `emails`
FOR EACH ROW BEGIN INSERT INTO obavijest (id, email, kategorija)
VALUES (NEW.id, NEW.email, NEW.kategorija);
END
Only thing left is to create a php script for getting emails from table 'obavijest' and send to this email addresses and run it with cron job.

MySQL InnoDB auto increment column based on combination of other columns

I am making a system where users can upload any file they want, and not use it to execute any kind of code. As a part of that, I rename every file, and store its original name in a MySQL table. This table contains the id of the user who uploaded it, and a unique id of the upload. Currently I am doing it like this:
CREATE TABLE `uploads` (
`user_id` INT(11) NOT NULL,
`upload_id` INT(11) NOT NULL AUTO_INCREMENT,
`original_name` VARCHAR(30) NOT NULL,
`mime_type` VARCHAR(30) NOT NULL,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`user_id`, `upload_id`)
) ENGINE=MyISAM;
This means I will always have a unique combination of user_id and upload_id, and every users first upload has an id of 1. However I heard MyISAM is old, and i should rather use InnoDB.
Is there any way I can achieve this in InnoDB?
The biggest problem with MyISAM tables is that they are not transactional. From what you say, you will only be creating records and then reading them (possibly deleting them later) but there will be little or no editing. This situation is what MyISAM was designed for, it is fast for mostly read only records. Personally I see no advantage converting to InnoDB.

PhpMyAdmin SQL code not showing up when creating new database and table

I'm using WampServer with phpmyadmin, but have also tried Xamp and same results.
I have 6 entries in the table called employees:
I have a table called employee with entries:
empId, lastName, firstName, department, position, and salary.
empId is primary key w/ auto increment. I'm following a tutorial online where they are using a mac computer, I'm on windows, in case that has something to do with the issue.
When I look at the SQL this produces it shows this:
SELECT * FROM `employee` WHERE 1
I don't see any CreateTable or other SQL.
Can anyone shed some light as to what is going on here?
Thank you.
UPDATE:
So if I go to > Export to SQL:
And this is what I get:
CREATE TABLE IF NOT EXISTS employee (
empId int(11) NOT NULL,
lastName varchar(40) NOT NULL,
firstName varchar(20) NOT NULL,
department int(2) NOT NULL,
position varchar(20) NOT NULL,
salary int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE employee
ADD PRIMARY KEY (empI);
Which looks like the correct SQL.
So at least I know it is creating the correct SQL even though its not showing on the phpmyadmin web gui page.
A CREATE TABLE statement is just a command to create a table. You can also create a table using the GUI of PHPMyAdmin, in which case it performs the necessary actions for you.
But those are just commands, blue-prints if you like. In the database itself the 'Create table' statement doesn't exist. The database contains an actual table which was created using such a statement. When you export the database (like you did) or ask for the create table statement, it just reverse-engineers the actual table structure into a statement, like drawing a blue-print based on an actual object you have.
PHPMyAdmin will often show the statement that it generated to build -for instance- a table, but in some cases you may not see it. It might be that the guy of the tutorial has a slightly different version of PHPMyAdmin, or he activated a feature that shows the statement.

Problem creating a reference table in mysql using php

I am creating a two MySQL tables in PHP, using the code as given below:
$sql = "CREATE TABLE qotwMember
(
MemberId NOT NULL PRIMARY KEY,
Name varchar(255),
Passwork varchar(255),
emailId varchar(255),
)";
$sql = "CREATE TABLE qotwQuestion1111
(
QuestionId NOT NULL AUTO_INCREMENT,
Question varchar(5000),
MemberId varchar(255) FOREIGN KEY fkname REFERENCES qotwMember(MemberId),
PostDate date,
Vote int,
PRIMARY KEY (QuestionId)
)";
mysql_query($sql,$con);
Then i try to insert data into these tables. In the qotwMember table, the data gets entered, but when I try to insert data into the qotwQuestion1111 table, it gives me the error "Error: Table 'database1.qotwQuestion1111' doesn't exist"
I can not figure out what I am doing wrong here. Please help me with this problem.
Note: Both the tables have been created in a different php.
Regards
Zeeshan
Are you sure you are selecting the right database each time? See: mysql_select_db()
I suspect you're not giving us the real SQL because neither of those statements will actually work - you're missing the datatype for the primary column and have some extra commas.
If that is your real SQL, then make sure you put or die(mysql_error($con)); after calls to mysql_query
When you are creating your tables, it is probably easier to use a MySQL front end such as MySQL query browser instead of trying to run the CREATE TABLE statements inside PHP. My guess is there is a syntax error in your second statement, so the table is not getting created. The front end will show you what the syntax error is.
Alternatively, you could check the return value of mysql_query to see if there is an error, and then use mysql_error() to read it out.
I have had the same problem as you with foreign key creation in MySQL (which is what your error is about).
When creating foreign keys, both the foreign key column and the reference column must be of the same data type and size. I noticed you did not give your primary key column any datatype or size. This is probably what is causing your error. Also, as others have pointed out, what engine you are using also will dictate if you can use foreign keys.
If you declare 'MemberID' as 'MemberID varchar(255) NOT NULL PRIMARY KEY' it should work as you have it now. I would suggest always giving your primary key columns a datatype and possible size. I don't know what your tables are for, but for a primary key column that is just an ID, i would recommend making it an INT of some sort (just remember to change your foreign key column to reflect that change).

Categories