Mysql Create Table If Not Exists else.... Information Schema - php

Quick one hopefully - not sure where I'm going wrong here but this doesn't seem to work full stop.
Running MySQL query through PHP...
Current code
$uu = mysql_query("
IF EXISTS(SELECT table_name FROM information_schema.tables
WHERE table_schema = 'schema_example' AND table_name = 'test_q')
THEN
insert into `test_q` (code, va_desc, price, category)
values ('$code', '$desc', '$price', '$categ')
on duplicate key update va_desc='$desc', price='$price', category='$categ'
ELSE
CREATE TABLE `test_quote` (
`code` varchar(30) NOT NULL,
`va_desc` text NOT NULL,
`price` text NOT NULL,
`category` text NOT NULL,
PRIMARY KEY (`code`),
UNIQUE KEY `id` (`code`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
insert into `test_q` (code, va_desc, price, category)
values ('$code', '$desc', '$price', '$categ')
END IF;
")or die(mysql_error());
Really appreciate some help on what I need to change, at the moment this does absolutely nothing and doesn't return any specific errors. :/
Having said that if I run it in phpMyAdmin it returns the following (although I can't understand why):
#1064 - You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server
version for the right syntax to use near
'ELSE CREATE TABLE `test_quote`(
`code` varchar(30) NOT NULL,
`va_desc` text NO' at line 7

You don't need to query INFORMATION_SCHEMA. You can use the IF NOT EXISTS option to CREATE TABLE.
mysql_query("CREATE TABLE IF NOT EXISTS `test_q` (
`code` varchar(30) NOT NULL,
`va_desc` text NOT NULL,
`price` text NOT NULL,
`category` text NOT NULL,
PRIMARY KEY (`code`),
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1");
mysql_query("insert into `test_q` (code, va_desc, price, category)
values ('$code', '$desc', '$price', '$categ')
on duplicate key update va_desc='$desc', price='$price', category='$categ'");
Also, a primary key is a unique key, you don't need to specify them both when you create the table.

Trying using the following query as if, else and then statements are not supported in the sql query, for that you can stored procedures.
mysql_query("CREATE TABLE IF NOT EXISTS `test_q` (`code` varchar(30) NOT NULL,
`va_desc` text NOT NULL,
`price` text NOT NULL,
`category` text NOT NULL,
PRIMARY KEY (`code`),
);
mysql_query("insert into `test_q` (code, va_desc, price, category)
values ('$code', '$desc', '$price', '$categ')
on duplicate key update va_desc='$desc', price='$price', category='$categ'");

Related

get the foreign key [duplicate]

This question already has answers here:
MYSQL - Impossible to create an external key
(1 answer)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
I am a self taught programmer in college and I am super confused since few days. I am working on the backend of a job listing website. The user will be able to post a job and I have three tables: jobs, keywords and requirements. The job_id is the primary key of jobs and also a foreign key in the keywords table. Right now, I am only able to insert data in the jobs table and I am not able to key anything from the keywords table. Each job_id can have multiple keyword.
SQL - jobs table
CREATE TABLE `jobs` (
`title` text NOT NULL,
`type` text NOT NULL,
`location` text NOT NULL,
`salary` int(11) NOT NULL,
`description` text NOT NULL,
`date` date NOT NULL,
`job_id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=latin1;
SQL - keywords table
CREATE TABLE `keywords` (
`keyword_id` int(11) NOT NULL AUTO_INCREMENT,
`keyword` text NOT NULL,
`job_id` int(11) NOT NULL,
PRIMARY KEY (`keyword_id`),
KEY `job_id` (`job_id`),
CONSTRAINT `keywords_ibfk_1` FOREIGN KEY (`job_id`) REFERENCES `jobs` (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;
PHP (I know the code is not secured yet but I just want to understand first)
<?php
require("../config/db.php");
require("add-jobs.php");
$link = mysqli_connect("localhost","root","","benoit");
$title = $_POST["position"];
$type = $_POST["job-type"];
$location = $_POST["location"];
$salary = $_POST["salary"];
$description = $_POST["description"];
$date = $publisheddate;
$keywords = $_POST["keywords"];
mysqli_query($link,"INSERT INTO jobs (`title`, `type`, `location`, `salary`, `description`, `date`)
VALUES ('$title', '$type', '$location', '$salary', '$description', CURDATE())")
or die(mysqli_error($link));
foreach ($keywords as $keyword){
mysqli_query($link, "INSERT INTO keywords (`keyword`) VALUES ('$keyword')");
}
?>
Get insert id with $mysqli->insert_id and use it:
mysqli_query($link, ".....");
$insert_id = mysqli_insert_id($link);
foreach ($keywords as $keyword){
mysqli_query($link, "INSERT INTO keywords (`job_id`, `keyword`) VALUES ($insert_id, '$keyword')");
}

error on local mysql but not on RDS mysql

I have a mysql insert query which runs on aws RDS(Live env) but throws an error on my local(local env).
on local I'am using mysql V-5.6
$sql = "INSERT INTO `users` (`id`,
`name`,
`email`,
`pass`)
values('','omi','omi#gmail.com','123123')
id is not null and auto_increment.
The error which i get on local is 'Incorrect integer value: '' for column 'id' at row 1'
but when this executed on live env all the data gets inserted into table.
I cant understand what exactly is happening here. please help. thank you.
DDL of users table.
local
CREATE TABLE `users`
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(256) DEFAULT '',
`email` varchar(256) NOT NULL,
`pass` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25986 DEFAULT CHARSET=utf8;
Live
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(254) DEFAULT '',
`email` varchar(256) NOT NULL,
`pass` varchar(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=26046 DEFAULT CHARSET=utf8;
I believe the error is with those quotes (''). When you want to do an insert with an auto_increment field, you have to use null as argument in the auto_increment field position.
See if this works:
$sql = "INSERT INTO `users`
(`id`, `name`, `email`, `pass`)
values(null,'omi','omi#gmail.com','123123');
EDIT 1
Using null doesn't generate any error because internally the DBMS is prepared to receive such an argument. It understands that is its duty to generate the next number of the sequence and if it hasn't any, 0 (of type integer in your case) is inserted first. I know defining "not null" in the DDL of a field and then using "null" in the DML insert statement for that exact field may look confusing, but it's just the right way to use the auto_increment feature.
From the documentation:
If the column is declared NOT NULL, it is also possible to assign NULL to the column to generate sequence numbers.
Also, if using an empty string as argument in an statement doesn't generate any error, it could maybe be because RDS interface has an internal function that converts empty to null. Something like the nullif function in MySQL.
You can't do it like that. Either dont even mention 'id' or give it null value.
$sql = "INSERT INTO `users` (
`name`,
`email`,
`pass`)
values('omi','omi#gmail.com','123123')
OR:
$sql = "INSERT INTO `users` (`id`,
`name`,
`email`,
`pass`)
values('NULL','omi','omi#gmail.com','123123')

Make new users automatically follow a user

I am working on a php site with uses mysql as database, now my site is a social network like site where users follow each other, now if a user joins in he is following nobody so his stream remains empty so they leave the site quickly as well,i want users to be following my account account automatically when he joins in. Can you please tell me how to do it
here are the two tables
Table structure for table sn_users
CREATE TABLE IF NOT EXISTS `sn_users` (
`id` int(11) NOT NULL,
`username` varchar(225) NOT NULL,
`email` varchar(225) NOT NULL,
`password` varchar(225) NOT NULL,
`name` varchar(225) DEFAULT NULL,
`picture` varchar(100) NOT NULL,
`cover` varchar(100) DEFAULT NULL,
`job` varchar(225) DEFAULT NULL,
`address` varchar(225) DEFAULT NULL,
`date` int(11) NOT NULL,
`reg_id` text,
`active` int(11) NOT NULL DEFAULT '1'
) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
Table structure for table sn_follows
CREATE TABLE IF NOT EXISTS `sn_follows` (
`id` int(11) NOT NULL,
`from` int(11) NOT NULL,
`to` int(11) NOT NULL,
`date` int(11) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=74 DEFAULT CHARSET=utf8;
Run the query when the user get registerd.
<?
//Register query
$con = mysqli_connect("[HOST", "[USER]", "[PASS]", "[DB]");
$query1 = "INSERT INTO sn_users
(username, email, password, name, picture, cover, job, address, date, reg_id, active)
VALUES
('$username', '$email', '$password', '$name', '$picture', '$cover', '$job', '$address', 'date', 'reg_id', 'active')";
mysqli_query($con, $query);
//Auto follow query
$query2 = "INSERT INTO sn_follows
(`id`, `from`, `to`, `date`)
VALUES
([ID], '[NEW REGISTERD ACCOUNT], '[YOUR ACCOUNT]', '[DATE]')";
mysqli_query($con, $query2);
Hints:
Make of the field id in your database an auto_increment
Make sure you put a hashed password in the database
you need to do some modifications in your script.
1) get last inserted id of new registered user
2) insert that last id in sn_follows table with your id
this may elaborate flow
after your user register insert query get last id like below
example:
$sql = "INSERT INTO sn_users (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$sqlfloow = "insert into sn_follows (from,to,date) values("your id",$last_id,date("Y-m-d H:i:s"))";
}

How to check if column 1 has two different values for column 2

I am trying to make a INSERT by UNIQUE and I am getting stuck, What I want too know is how I would do is make it so Column A is ALWAYS UNIQUE unless Column C has two different values and then it will insert into the database a second row for Column A where Column C is different.
a|b|c
-----
1|2|3
2|4|5
1|6|7
So I am currently using this sql table
CREATE TABLE `Player` (
`id` int(11) NOT NULL auto_increment,
`playername` varchar(255) NOT NULL,
`SteamID` varchar(255) NOT NULL UNIQUE,
`position` varchar(255) NOT NULL,
`lastlogin` varchar(255) NOT NULL,
`approved` varchar(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
With this query
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
It inserts the way I want so there is only 1 of each SteamID but it also will not insert if the same SteamID has two values for position.
EDIT:
What I have is a xml file I load up and insert data into the database based on the data in the xml file, What I need is below.
$xml = simplexml_load_file("players.xml");
foreach($xml->children() as $player)
{
$id = $player->attributes()->id;
$profile = new SteamProfile($id);
$name = mysql_real_escape_string($profile->getUsername());
$lastlogin = $player->attributes()->lastlogin;
$position = $player->lpblock->attributes()->pos;
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
if (!mysql_query($sql1,$connection))
{
die('Insert Error: ' . mysql_error());
}
}
so the xml file gets read and then the data in the file gets inserted into the database. sometimes the xml file would contain
<player id="76561197961716203" lastlogin="8/22/2014 10:49:28 PM">
<acl id="76561197961543041"/>
<acl id="76561197988417990"/>
<lpblock pos="273,93,-102"/>
<lpblock pos="1322,62,-1711"/>
</player>
at which point I would need a second row created for the second <lpblock pos=
So its currently inserting
|60|SwordFish |76561197961716203|273,93,-102|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
and it should be inserting
|60|SwordFish |76561197961716203|273,93,-102|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
|61|SwordFish |76561197961716203|1322,62,-1711|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
I'm not sure what you are trying to achieve, but you can set a UNIQUE restraint on a combination of columns, in your case SteamID and position:
CREATE TABLE `Player` (
`id` int(11) NOT NULL auto_increment,
`playername` varchar(255) NOT NULL,
`SteamID` varchar(255) NOT NULL,
`position` varchar(255) NOT NULL,
`lastlogin` varchar(255) NOT NULL,
`approved` varchar(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_combination_of_two_fields` (`SteamID`,`position`)
) ENGINE=InnoDB;
Thanks for you help Jeroen I did this and its working.
foreach($player->children() as $lpblock)
{
$position = $lpblock->attributes()->pos;
if(!empty($position))
{
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
if (!mysql_query($sql1,$connection))
{
die('Insert Error: ' . mysql_error());
}
}
}
However I would like all of the SteamID's inserted and not just the ones with a $position set. When I take this out and try it adds the correct rows but also adds another row with a blank $position as if there is a SteamID that's blank when there is none.
if(!empty($position)){
}

Paypal IPN - store data on database, update and delete

I'm using this example to store in the database the info coming from PayPal, my problem is that the database create two records for the same sale, one with the status of 'Pending' and one with the status 'Completed', both for the same sale.
How can I change this part of the code so if there is a sale with the same 'txn_id' I just update the 'payment_status' row OR delete the whole thing before update it with the new info. Note that there is two rows that will be different, 'payment_status' and 'createdtime' .
function updatePayments($data){
global $link;
if(is_array($data)){
$sql = mysql_query("INSERT INTO `payments` (txnid, payment_amount, payment_status, item_name, receiver_email, payer_email, custom, itemid, createdtime) VALUES (
'".$data['txn_id']."' ,
'".$data['payment_amount']."' ,
'".$data['payment_status']."' ,
'".$data['item_name']."' ,
'".$data['receiver_email']."' ,
'".$data['payer_email']."' ,
'".$data['custom']."' ,
'".$data['itemid']."' ,
'".date("Y-m-d H:i:s")."'
)", $link);
return mysql_insert_id($link);
}
}
Database structure
CREATE TABLE IF NOT EXISTS `payments` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`txnid` varchar(20) NOT NULL,
`payment_amount` decimal(7,2) NOT NULL,
`payment_status` varchar(25) NOT NULL,
`item_name` varchar(50) NOT NULL,
`receiver_email` varchar(50) NOT NULL,
`payer_email` varchar(50) NOT NULL,
`custom` varchar(25) NOT NULL,
`itemid` varchar(25) NOT NULL,
`createdtime` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Create a UNIQUE INDEX on txn_id (if one doesn't exist already) and then use either INSERT ... ON DUPLICATE KEY UPDATE or REPLACE in place of your existing INSERT.
UPDATE
In your case, to add the unique index:
ALTER TABLE payments ADD UNIQUE INDEX (txnid);
Then, append to the end of your INSERT statement:
ON DUPLICATE KEY UPDATE payment_status = '".$data['payment_status']"'
If you want to delete the existing record and replace it with your new one, just change the word INSERT to REPLACE instead.

Categories