0

I am struggling to get the proper syntax for a SQL query. I have looked through all I can but cant seem to get anything that works.

I want to check to see if a record is in the database e.g.

SELECT Date,Time FROM loadings WHERE Date='21-06-2011' AND Time ='7'

If it does then I can update it, if it doesnt I need to add it first before I can cary out some operations.

I tried

[php]

IF EXISTS(SELECT Date,Time FROM loadings WHERE Date='21-06-2011' AND Time ='7')
{
// Record exists do nothing
}
else
{
// Insert record
INSERT Date,Time INTO loadings VALUES Date='21-06-2011' AND Time ='7'
}

[/php]

Can anyone guide me on the correct syntax to use.

By the way just founf this site and reading through seems excellent. Particularly the suggestions given from previos submissions to answer the question. I look through all them but didn't find my answer.

Regards Trevor

ypercubeᵀᴹ
  • 105,605
  • 14
  • 160
  • 222

3 Answers3

1

You need something like the code below

<?php

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT Date,Time FROM loadings WHERE Date='21-06-2011' AND Time ='7'", $link);
$num_rows = mysql_num_rows($result);

if $num_rows == 0 { code to insert } /* when query returns no rows insert into the database*/

?>
niktrs
  • 8,663
  • 1
  • 25
  • 27
1

In Summary: Don't use reserved words.

It looks like you are using reserved words. using reserved words make for very tricky bugs.

for your reserved fields and variables i'd add the or a or some sort of prefix.

adate instead of date
atime instead of time

to see the list of reserved words go here.

http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

Gidon Wise
  • 1,868
  • 1
  • 11
  • 10
0
$rs = mysql_query("SELECT Date,Time FROM loadings WHERE Date='21-06-2011' AND Time ='7'");
$row = mysql_fetch_array($rs);
$num = mysql_num_rows($rs);

if($num > 0) {
//Does nothing
} else {
//insert here
}
easyb
  • 68
  • 1
  • 8