if specific row = null, execute query - mysql

how do i check if the value of a column is null, and only then execute the query? for example:
col1 col2 col3
01 abc
i run a query which first checks if the record exists or not; if it exists, it should execute the update query and if it doesn't exist, it executes the insert query. how do i check if col3 is null and if it is null, it should execute the update query. .
$sql = "SELECT uid FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
insertUser($user_id,$sk, $conn);
}
else
{
updateSessionKey($user_id,$sk,$conn);
}

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Not really checking a value of the column, but I don't think you actually need that.
You need to have uid as a UNIQUE column. You try to insert a row for a new user with the given uid; if it finds the user with the same uid, then you do the update instead.
UPDATE:
I guess you did not bother to read the link.
I did not test it, but it should be something like this:
INSERT INTO users (uid, name, session)
VALUES ('login', 'Real Name', 'SeSsIoN_iD')
ON DUPLICATE KEY UPDATE session='SeSsIoN_iD'
This will insert the user if he does not exist, and if he does, it will set a new session key. OR, if you want to preserve the old session key if he already has one,
INSERT INTO users (uid, name, session)
VALUES ('login', 'Real Name', 'SeSsIoN_iD')
ON DUPLICATE KEY UPDATE session=IFNULL(session, 'SeSsIoN_iD')
One query, not three. You were not already doing it.

$sql = "SELECT * FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
$res = mysql_fetch_array($sql);
if(!empty($res['col3'])) {
insertUser($user_id,$sk, $conn);
}
}
else
{
updateSessionKey($user_id,$sk,$conn);
}

Is this what you mean?
If the record does not exist -> insert.
If the record does exist and its col3 is null -> update
If the record does exist, but its col3 is not null -> do nothing?
That could be achieved like this (untested):
$sql = "SELECT uid, col3 FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
insertUser($user_id,$sk, $conn);
}
else
{
$col3value = mysql_result($result, 0, 'col3');
if (is_null($col3value))
{
updateSessionKey($user_id,$sk,$conn);
}
}

Related

What is fastest way to update multiple columns in a table from data of another table where updating table column(s) are something?

I have these two queries which work, but they are slow as can be. What is faster, or rather fastest way of doing this?
method 1)
$query = "
UPDATE list_data_extra
INNER JOIN list_data
ON (list_data_extra.serial_no = list_data.serial_no)
SET
list_data_extra.id = list_data.id,
list_data_extra.cid = list_data.cid,
list_data_extra.first = list_data.first,
list_data_extra.last = list_data.last,
list_data_extra.tracking_number = list_data.tracking_number
WHERE list_data_extra.id='0' AND list_data_extra.cid='0'
";
method 2)
$query = "UPDATE list_data_extra
INNER JOIN list_data USING (serial_no)
SET list_data_extra.id = list_data.id,
list_data_extra.cid = list_data.cid,
list_data_extra.first = list_data.first,
list_data_extra.last = list_data.last,
list_data_extra.tracking_number = list_data.tracking_number
WHERE list_data_extra.id='0'
AND list_data_extra.cid='0'";
Not sure this other method would be faster:
method 3)
$query="SELECT * FROM list_data_extra WHERE id='0' AND cid='0'";
$result=mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
while($row=mysql_fetch_array($result)) {
$querytwo = mysql_fetch_array(mysql_query(
"SELECT id, cid, first, last, tracking_number
FROM list_data
WHERE serial_no='".$row['serial_no']."'"), MYSQL_ASSOC);
$querythree = "UPDATE list_data_extra
SET id='".$querytwo["id"]."', cid='".$querytwo["cid"]."',
first='".$querytwo["first"]."', last='".$querytwo["last"]."',
tracking_number='".$querytwo["tracking_number"]."'";
mysql_query($querythree);
}
}
Another thing i tried is this, which is building entire query then executing it all at once, which is a bit faster than above, but still slow as junk. the above is like 9 minutes per 1000 records and this here below is like 5 minutes per 1000.
method 4)
$query="SELECT * FROM list_data_extra WHERE id='0' AND cid='0'";
$result=mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$id_loop = "";
$cid_loop = "";
$first_loop = "";
$last_loop = "";
$trackingnumber_loop = "";
$listids = "";
while($row=mysql_fetch_array($result)) {
$querytwo = mysql_fetch_array(mysql_query("SELECT id, cid, first, last, tracking_number FROM list_data WHERE serial_no='".$row['serial_no']."'"), MYSQL_ASSOC);
$id_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["id"]."' ";
$cid_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["cid"]."' ";
$first_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["first"]."' ";
$last_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["last"]."' ";
$trackingnumber_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["tracking_number"]."' ";
$listids .= ", ".$row['listid'];
}
$listidsb = substr($listids, 2);
$querythree = "UPDATE list_data_extra
SET
id = CASE listid
".$id_loop."
END,
cid = CASE listid
".$cid_loop."
END,
first = CASE listid
".$first_loop."
END,
last = CASE listid
".$last_loop."
END,
tracking_number = CASE listid
".$trackingnumber_loop."
END
WHERE listid IN (".$listidsb.")";
mysql_query($querythree) or die(mysql_error());
}
Is there a better and faster way to update multiple columns in many records in one table with data from another table?
CREATE TABLE list_data (
id int(11) NOT NULL AUTO_INCREMENT,
cid int(11) NOT NULL,
first varchar(255) NOT NULL,
last varchar(255) NOT NULL,
tracking_number varchar(255) NOT NULL,
serial_no varchar(9) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=555555 DEFAULT CHARSET=latin1
Unindexed JOIN and WHERE conditions can be slow, especially if they involve string data; try running these two (they make take a little time to run if the tables are large), and then trying your original query again.
ALTER TABLE list_data
ADD INDEX serial_idx (serial_no);
ALTER TABLE list_data_extra
ADD INDEX serial_idx (serial_no);

How to update array of records if not exist insert, without id?

i tried to do like this:
INSERT INTO hlr_client_country
(perform_hlr, client_id, mcc, dial_code)
VALUES
(1,2,202,30),(1,2,204,31)
ON DUPLICATE KEY UPDATE
id = 'id',
client_id = 'client_id',
mcc = 'mcc'
but query always inserts new and new records.
I want to update first and if record not exists insert one
Help please
try this code
$result = mysql_query("SELECT * FROM table WHERE title_1 ='$title_1' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE table SET column = '$value' WHERE title_1 = '$title_1' ");
}
else
{
mysql_query("INSERT INTO table (title_1) VALUES ('$title_1') ");
}
^_^

mysql, if row exists incrament value else insert row without key

I'm trying to do something that may be too complicated for MySQL
If a row exists i'd like it to update a counter and if not insert the row...I did a search and found this...
$query = "insert into TABLE
(`id`, `item`, `count`, `option1`, `option2`)
values
('$cartName', '$sku', 1, '$option1', '$option2')
on duplicate key
update count = count + 1";
but I don't have a key in the table so the "on duplicate key" won't work, the query needs multiple ANDs to check the row based on the id, item, and 2 option values.
an added thing is to have mySQL return a count of all count values based on the item
This is what I have currently (modified from search :), does anyone know how to reduce this into a single query?
option1 and option2 are variable and could be null so that's why the 2 if statements and is called from AJAX so the $message is used to update the javascript client side.
$query = "update TABLENAME set count=count+1 where item='$item'";
if($option1) $query .= " AND option1='$option1'";
if($option2) $query .= " AND option2='$option2'";
$result = mysql_query($query) or die("Error:".mysql_error() );
if (mysql_affected_rows()==0) {
$query = "insert into $table11 (`id`, `item`, `count`, `option1`, `option2`) values ('$id', '$item', 1, '$option1', '$option2');";
$result = mysql_query($query) or die("Error:".mysql_error() );
}
//total count for all items with specific id
$query = "SELECT SUM(count) FROM TABLENAME WHERE id='$cartName'";
$result = mysql_fetch_row(mysql_query($query)) or die("Error:".mysql_error() );
$message = $result[0];

joomla database select and insert query

i am trying to insert another info to joomla (2.5.7) database after user is registered. The user chooses his usergroup and I want the insertion to happen only when the user is in a specific group. So I am trying to use this code to get the group data from the databse first to be used in the insert query. Now it is just a testing ground, later this retrieved value be used in if statement.
This is the code:
function onUserAfterSave($user, $isnew, $success, $msg)
{
if ($isnew && $success) {
$db = &JFactory::getDBO();
$query = "SELECT #__k2_users.group FROM #__k2_users WHERE userID = ".$user['id'];
$db->setQuery($query);
$group = $db->loadResult();
$db->setQuery( 'INSERT INTO #__user_profiles (ordering) VALUES ('.$group.')' );
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
return $this->onAfterStoreUser($user, $isnew, $success, $msg);
}
and this is the error I am getting upon the failed registration:
Column count doesn't match value count at row 1 SQL=INSERT INTO std13_user_profiles (ordering) VALUES ()
If I read it correctly, it means that the select statement is not returning anything but why? Thank you for your help.
UPDATE:
if ($isnew && $success) {
$db = &JFactory::getDBO();
$userId = JArrayHelper::getValue($user, 'id', 0, 'int');
$query = "SELECT #__k2_users.group FROM #__k2_users WHERE userID = ".$userId;
$db->setQuery($query);
$group = $db->loadResult();
$query2 = "INSERT INTO #__user_profiles (ordering) VALUES ('".$group."')";
$db->setQuery($query2);
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
with this code, I don't get any errors and the user is registered and the values are inserted. However the $group is always 0 and based on the value is only 1 or 3 in k2_users table, I am guessing that it returns nothing. I think it may be because the registered user is not stored in the databse yet and it doesn't have his ID yet to look for the group?
UPDATE2:
if ($isnew && $success) {
$count = JRequest::getVar('gender');
if($count == 3) {
$db = &JFactory::getDBO();
$alias = $user['name'];
$table = array(
' '=>'-', 'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj', 'Ž'=>'Z', 'ž'=>'z', 'C'=>'C', 'c'=>'c', 'C'=>'C', 'c'=>'c',
'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
'Õ'=>'O', 'Ö'=>'O', 'ě'=>'e', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
'ÿ'=>'y', 'R'=>'R', 'r'=>'r', " "=>'-', '"'=>'-'
);
$string = strtr($alias, $table);
$alias_low = strtolower($string);
$query = "INSERT INTO #__menu (menutype, title, alias, path, link, type, published, level, component_id, access) VALUES ('stavebnici','".$user['name']."','".$alias_low."','".$alias_low."',
'index.php?option=com_k2&view=itemlist&layout=user&id=".$user['id']."&task=user','component',1,1,10012,1)";
$db->setQuery($query);
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
}
OKAY! I got it working so now I can insert new menu every time a user is created, however th activation link is not created and the registration says that it failed. This is the error:
Duplicate entry '0-1-vojtech-plesner-' for key 'idx_client_id_parent_id_alias_language' SQL=INSERT INTO std13_menu (menutype, title, alias, path, link, type, published, level, component_id, access) VALUES ('stavebnici','Vojtěch Plešner','vojtech-plesner','vojtech-plesner', 'index.php?option=com_k2&view=itemlist&layout=user&id=2789&task=user','component',1,1,10012,1)
The client_id, parent_id and language have values of 1,1 and * abd they are in all the rows so why is it saying it is duplicate?
You need to update that query to 2.5 style.
http://www.theartofjoomla.com/home/9-developer/135-database-upgrades-in-joomla-16.html
is a good article.
You definitely seem to be missing
$query = $db->getQuery(true);
not to mention that you are using & for an object. That usage will generate strict errors.
You can do it with one query:
$query = "
INSERT INTO #__user_profiles (ordering)
SELECT #__k2_users.group
FROM #__k2_users
WHERE userID = " . user['id']
";
But doesn't #__user_profiles have other columns like the user id?
Also You can do it with one query:
$query = "
INSERT INTO #__user_profiles (ordering)
SELECT "YOURJOOMLADBPREFIX"_k2_users.group
FROM "YOURJOOMLADBPREFIX"_k2_users
WHERE userID = " . user['id']
";

Insert on first request; update on all subsequent requests

I'm inserting a row into a MySQL database table. On the first insertion I want a new row to be added, but after that I just want that row to be updated. Here's how I'm doing it. An Ajax request calls the following php file:
<?php
include "base.php";
$bookID = $_POST['bookID'];
$shelfID = $_POST['shelfID'];
$userID = $_SESSION['user_id'];
$query = mysql_query("SELECT shelfID FROM shelves WHERE userID = '$userID' AND shelfID = '$shelfID' AND bookID = '$bookID'");
if (mysql_num_rows($query) == 0) {
$insert = "INSERT INTO shelves (bookID,shelfID,userID) VALUES ('$bookID','$shelfID','$userID')";
mysql_query($insert) or die(mysql_error());
} elseif (mysql_num_rows($query) == 1) { //ie row already exists
$update = "UPDATE shelves SET shelfID = '$shelfID' WHERE userID = '$userID' AND bookID = '$bookID'";
mysql_query($update) or die(mysql_error());
}
?>
As it stands it adds a new row every time.
You should consider using PDO for data access. There is a discussion on what you need to do here: PDO Insert on Duplicate Key Update
I'd flag this as duplicate, but that question is specifically discussing PDO.
You can use the INSERT ... ON DUPLICATE KEY UPDATE syntax. As long as you have a unique index on the data set (i.e. userid + shelfid + bookid) you are inserting, it will do an update instead.
http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html