I got this table
CREATE TABLE IF NOT EXISTS `set_indice_cuestionarios` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cuestionario` int(11) NOT NULL,
`fecha` date NOT NULL,
`hora` time NOT NULL,
`aplico` varchar(100) NOT NULL,
`cliente` int(11) NOT NULL,
`tienda` int(11) NOT NULL,
`status` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `tienda` (`tienda`),
UNIQUE KEY `cuestionario` (`cuestionario`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
And this is my SQL sentence:
$sql_indice = "INSERT INTO set_indice_cuestionarios (cuestionario, fecha, hora, aplico, cliente, tienda) values('$cuestionario','$fecha','$hora','$aplico','$cliente','$tienda') ON DUPLICATE KEY UPDATE cuestionario = '$cuestionario', fecha = '$fecha', hora = '$hora', aplico = '$aplico', cliente = '$cliente', status = 0";
I want to Update a row if $tienda = tienda and $cuestionario = cuestionario and to Insert a new one if the any of the values doesn't match.
The Update is happening when both values match but when I only change $cuestionario it Updates the table, instead of inserting a new record, and when I only change $tienda it does the Insert. I have no idea what I' am doing wrong. Thank you in advance!
Related
I found this useful Internationalization code:
http://pastebin.com/SyKmPYTX
everything works well except I am unable to connect to database.
what I need:
1) I need to check last segment
2) this is my db
DROP TABLE IF EXISTS `translate`;
DROP TABLE IF EXISTS `trans_data`;
DROP TABLE IF EXISTS `languages`;
/*Table structure for table `languages` */
CREATE TABLE `languages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`key` varchar(5) NOT NULL,
`default` tinyint(1) NOT NULL DEFAULT '0',
`display` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
/*Data for the table `languages` */
insert into `languages`(`name`,`key`,`default`,`display`) values
('GEO','ka',1,1),
('ENG','en',0,1),
('RUS','ru',0,1);
/*Table structure for table `trans_data` */
CREATE TABLE `trans_data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
/*Table structure for table `translate` */
CREATE TABLE `translate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lang` int(11) NOT NULL,
`data` int(11) NOT NULL,
`trans` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `lang_2` (`lang`,`data`),
KEY `lang` (`lang`),
KEY `data` (`data`),
CONSTRAINT `translate_ibfk_1` FOREIGN KEY (`lang`) REFERENCES `languages` (`id`),
CONSTRAINT `translate_ibfk_2` FOREIGN KEY (`data`) REFERENCES `trans_data` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=340 DEFAULT CHARSET=utf8;
in the first I need to do something like this
$this->db->where('key', end($this->segments));
$query = $this->db->get('languages');
$lang = $query->row();
if(empty($lang)){
$this->db->where('default', 1);
$query2 = $this->db->get('languages');
$lang = $query2->row();
}
$lang_array = [
"lang_key" => $lang->key,
"lang_id" => $lang->id
];
$this->session->set_userdata($lang_array);
if(end($this->uri->segment_array()) == $lang->key){
unset($this->uri->segments[intval($this->uri->total_segments() - 1)]);
}
after this functionality
then I need to download translates from database and save it in object with this query
SELECT TD.`name` , T.`trans`
FROM `translate` AS T
INNER JOIN `languages` AS L ON (T.`lang` = L.`id`)
INNER JOIN `trans_data` AS TD ON (T.`data` = TD.`id`)
WHERE (L.`key` = :lang_key);
and when I call from view
echo $this->lang->line('trans_key');
I need to get the value
but I do not undestand how to edit this class to do this job...
can you help me and edit this class for me?
thank you for future...
When I trying to run the code, this error shows up
Cannot add or update a child row: a foreign key constraint fails
(hotel_info.results, CONSTRAINT results_ibfk_5 FOREIGN KEY
(CustomerID) REFERENCES customer (CustomerID) ON DELETE CASCADE
ON UPDATE CASCADE)
Here is the code
$result = mysql_query("select customer.CustomerID from customer inner join results on customer.CustomerID = results.CustomerID where customer.Username = '".$aid."'");
if (false === $result)
{
echo mysql_error();
}
if (isset($_POST["submitbtn"]))
{
$LP = $_POST["LP"];
$budget = $_POST["budget"];
$checkin = $_POST["CheckIn"];
$checkout = $_POST["CheckOut"];
$unit = $_POST["unit"];
$smokep = $_POST["SmokeP"];
$spreq = $_POST["sp_req"];
if($checkin>$checkout)
{
?>
<script type="text/javascript">
alert("End Date must greater than Start Date.");
</script>
<?php
}
else
{
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$result')");
if (false === $query)
{
echo mysql_error();
}
echo "Reservation form has been submitted!<br>
<a href=view.php>view all</a>";
}
}
Here is the sql
CREATE TABLE IF NOT EXISTS `results` (
`BookID` int(10) NOT NULL AUTO_INCREMENT,
`LP` varchar(50) DEFAULT NULL,
`budget` varchar(50) DEFAULT NULL,
`CheckIn` varchar(50) DEFAULT NULL,
`CheckOut` varchar(50) DEFAULT NULL,
`unit` int(50) DEFAULT NULL,
`SmokeP` varchar(50) DEFAULT NULL,
`sp_req` varchar(255) DEFAULT NULL,
`CustomerID` int(10) NOT NULL,
PRIMARY KEY (`BookID`),
KEY `Username` (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=48 ;
CREATE TABLE IF NOT EXISTS `customer` (
`CustomerID` int(10) NOT NULL AUTO_INCREMENT,
`Username` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`ContactNo` int(10) NOT NULL,
PRIMARY KEY (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
I've already stuck for two days because of this error, please help.
from the error it is clear that foreign key constraint fails. Please check your customer table which must have CustomerID that you are trying to insert in results table insert query i.e. check value of $id. have you assigned any value for $id
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$id')");
In above query value for $id not set so first assign value to that.
We have the following two tables:
CREATE TABLE IF NOT EXISTS `gp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`amount` decimal(15,2) NOT NULL,
`user` varchar(100) NOT NULL DEFAULT '',
`status` tinyint(2) NOT NULL DEFAULT '1',
`ip` varchar(20) NOT NULL DEFAULT 'N/A',
`token` varchar(100) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS `gp_logs` (
`id` int(11) NOT NULL,
`log` varchar(1000) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
We JOIN them, for statistics, but we do this rarely, since the data from the 2nd table is not used too often except when we need to verify things.
Considering that we have many queries per second, how can our query be optimized to use 1 INSERT query instead of two and to insert the correct id in the 2nd table (gp_logs) that was generated by the INSERT into table gp?
Right now, we do a combination of MYSQL with PHP:
mysqli_query($con,"INSERT INTO `gp` (amount,user) VALUES ('1234','1')");
$id = mysqli_insert_id($con);
mysqli_query($con,"INSERT INTO gp_logs(id,log) VALUES ('$id','some_data')");
We want to eliminate the requirement of PHP for getting the last inserted ID and to insert both entries by running a single INSERT query (with a JOIN).
Here's my info table:
CREATE TABLE `info` (
`id_info` int(10) NOT NULL auto_increment,
`judul_info` varchar(50) collate latin1_general_ci NOT NULL,
`konten` varchar(255) collate latin1_general_ci NOT NULL,
`diubah_oleh` varchar(20) collate latin1_general_ci NOT NULL,
`id_kategori` int(10) NOT NULL,
`tgl_buat` timestamp NOT NULL default '0000-00-00 00:00:00',
`tgl_ubah` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`dibuat_oleh` varchar(20) collate latin1_general_ci NOT NULL,
`id` int(10) NOT NULL,
PRIMARY KEY (`id_info`),
KEY `id_kategori` (`id_kategori`),
KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=62 ;
Here's my upload table
CREATE TABLE `upload` (
`id` int(10) unsigned NOT NULL auto_increment,
`deskripsi` text,
`filetype` varchar(200) default NULL,
`filedata` longblob,
`filename` varchar(200) default NULL,
`filesize` bigint(20) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ;
I'm using this query :
$sql1="INSERT INTO info VALUES('','$judul', '$konten','$diubah_oleh','$kategori',now(),'$tgl_ubah','$dibuat_oleh','')";
$sql2="insert into upload values ('','$keterangan','$tipe','$filedata','$nama_file',$ukuran)";
$sql3="UPDATE info SET id=last_insert_id()";
$result=mysql_query($sql1);
$result=mysql_query($sql2);
$result=mysql_query($sql3);
I want info.id has the same value as upload.id but with this query all of the value i get in info.id is the same as value i last inserted in upload.id.
CREATE TABLE `upload` (
`id` int(10) unsigned NOT NULL,
`deskripsi` text,
`filetype` varchar(200) default NULL,
`filedata` longblob,
`filename` varchar(200) default NULL,
`filesize` bigint(20) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ;
$sql1="INSERT INTO info VALUES('','$judul', '$konten','$diubah_oleh','$kategori',now(),'$tgl_ubah','$dibuat_oleh','')";
$result=mysql_query($sql1);
$lastId = mysql_insert_id();
$sql2="insert into upload values ('$lastId','$keterangan','$tipe','$filedata','$nama_file',$ukuran)";
$result=mysql_query($sql2);
Your last update statement below is updating all the rows in your info tables with the same id because there is no where statement.
Since you need the upload table id information inside the info table.
Follow these steps:
Run the $sql2 first.
Then run the $sql1 inserting the last_insert_id() in info.id.
This way you don't need to use update statement as well.
You can do this by using mysql_insert_id(). This function returns the AUTO_INCREMENT ID generated from the previous INSERT operation. Your code should look like this
$sql1="INSERT INTO info VALUES('','$judul', '$konten','$diubah_oleh','$kategori',now(),'$tgl_ubah','$dibuat_oleh','')";
$result=mysql_query($sql1);
$lastinsertedid= mysql_insert_id();
$sql2="insert into upload values ('$lastinsertedid','$keterangan','$tipe','$filedata','$nama_file',$ukuran)";
$result=mysql_query($sql2);
Hope this helps you
There is an alternate php function to that mysql_insert_id() . You can use this to generate the ID inserted in the last executed query.
can you try to do this:
$sql1="INSERT INTO info VALUES('','$judul', '$konten','$diubah_oleh','$kategori',now(),'$tgl_ubah','$dibuat_oleh','')";
$sql2="insert into upload values ('','$keterangan','$tipe','$filedata','$nama_file',$ukuran)";
$last_id = last_insert_id();
$sql3="UPDATE info SET id=".$last_id;
$result=mysql_query($sql1);
$result=mysql_query($sql2);
$result=mysql_query($sql3);
I have made some Vote script, where user vote up or down for some answers. It works fine when i have only one answer for question. If i give two or more answers for One question, the i got an error subquery returns more than one row.
$rezultati = mysqli_query($con,"SELECT SUM(down) as down
FROM vote WHERE answerId =
(SELECT questionId FROM answers WHERE questionId = $id)");
while($row = mysqli_fetch_array($rezultati))
{
echo $row['down'];
}
mysqli_close($con);
?>
This is for UP button, and for Down is similar. (I know that there is simplier way to make all that, but i am new at php..)
Here is table questions
CREATE TABLE IF NOT EXISTS `questions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`question` text NOT NULL,
`user` varchar(255) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
And table Answers
CREATE TABLE IF NOT EXISTS `answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`answer` text COLLATE utf8_unicode_ci NOT NULL,
`questionId` int(11) NOT NULL,
`user` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
)
And table Vote
CREATE TABLE IF NOT EXISTS `vote` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ip` varchar(50) NOT NULL,
`answerId` int(11) NOT NULL,
`up` int(11) NOT NULL,
`down` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
Where is the problem? How to fix that? Thank you!!
From your question I understand that you want to list all down votes for a certain question. Then, if you are updating the columns up and down to table answers, the query is simple.
"SELECT SUM(down) as down
FROM answers WHERE questionId = $id)"