joomla database select and insert query - mysql
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']
";
Related
Insert all in mysql [duplicate]
Assuming that I have two tables, names and phones, and I want to insert data from some input to the tables, in one query. How can it be done?
You can't. However, you CAN use a transaction and have both of them be contained within one transaction. START TRANSACTION; INSERT INTO table1 VALUES ('1','2','3'); INSERT INTO table2 VALUES ('bob','smith'); COMMIT; http://dev.mysql.com/doc/refman/5.1/en/commit.html
MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly... INSERT INTO NAMES VALUES(...) INSERT INTO PHONES VALUES(...)
Old question, but in case someone finds it useful... In Posgresql, MariaDB and probably MySQL 8+ you might achieve the same thing without transactions using WITH statement. WITH names_inserted AS ( INSERT INTO names ('John Doe') RETURNING * ), phones_inserted AS ( INSERT INTO phones (id_name, phone) ( SELECT names_inserted.id, '123-123-123' as phone ) RETURNING * ) SELECT * FROM names_inserted LEFT JOIN phones_inserted ON phones_inserted.id_name=names_inserted.id This technique doesn't have much advantages in comparison with transactions in this case, but as an option... or if your system doesn't support transactions for some reason... P.S. I know this is a Postgresql example, but it looks like MariaDB have complete support of this kind of queries. And in MySQL I suppose you may just use LAST_INSERT_ID() instead of RETURNING * and some minor adjustments.
I had the same problem. I solve it with a for loop. Example: If I want to write in 2 identical tables, using a loop for x = 0 to 1 if x = 0 then TableToWrite = "Table1" if x = 1 then TableToWrite = "Table2" Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')" NEXT either ArrTable = ("Table1", "Table2") for xArrTable = 0 to Ubound(ArrTable) Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')" NEXT If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.
my way is simple...handle one query at time, procedural programming works just perfect //insert data $insertQuery = "INSERT INTO drivers (fname, sname) VALUES ('$fname','$sname')"; //save using msqli_query $save = mysqli_query($conn, $insertQuery); //check if saved successfully if (isset($save)){ //save second mysqli_query $insertQuery2 = "INSERT INTO users (username, email, password) VALUES ('$username', '$email','$password')"; $save2 = mysqli_query($conn, $insertQuery2); //check if second save is successfully if (isset($save2)){ //save third mysqli_query $insertQuery3 = "INSERT INTO vehicles (v_reg, v_make, v_capacity) VALUES('$v_reg','$v_make','$v_capacity')"; $save3 = mysqli_query($conn, $insertQuery3); //redirect if all insert queries are successful. header("location:login.php"); } }else{ echo "Oopsy! An Error Occured."; }
Multiple SQL statements must be executed with the mysqli_multi_query() function. Example (MySQLi Object-oriented): <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "INSERT INTO names (firstname, lastname) VALUES ('inpute value here', 'inpute value here');"; $sql .= "INSERT INTO phones (landphone, mobile) VALUES ('inpute value here', 'inpute value here');"; if ($conn->multi_query($sql) === TRUE) { echo "New records created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
MySQL Trigger Won't Fire After Insert From Wordpress Endpoint
I want to delete all high scores except the top 10. My query works fine as a query in PHPMysql, but when I try to use it in a trigger, it doesn't fire. If anyone has a suggestion or needs additional information, please let me know. Thanks. //The query DELETE FROM ONEGameleaderboard WHERE _id Not IN (SELECT * FROM (SELECT _id FROM ONEGameleaderboard ORDER BY Score DESC , Date ASC LIMIT 10) as t) //The Trigger insert query CREATE TRIGGER `ONEGameleaderboardTop10Limit` AFTER INSERT ON `ONEGameleaderboard` FOR EACH ROW DELETE FROM ONEGameleaderboard WHERE _id Not IN (SELECT * FROM (SELECT _id FROM ONEGameleaderboard ORDER BY Score DESC , Date ASC LIMIT 10) as t) //The insert code form the WordPress endpoint (Which inserts the data just fine) // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $parameters = $request->get_json_params(); if($request['id'] == 1) { $sql = "INSERT INTO ONEGameleaderboard (Date, Name, Score) VALUES ('$parameters[Date]', '$parameters[Name]', '$parameters[Score]')"; } elseif($request['id'] == 2) { $sql = "INSERT INTO TWOGameleaderboard (Date, Name, Score) VALUES ('$parameters[Date]', '$parameters[Name]', '$parameters[Score]')"; } elseif($request['id'] == 3) { $sql = "INSERT INTO THREEGameleaderboard (Date, Name, Score) VALUES ('$parameters[Date]', '$parameters[Name]', '$parameters[Score]')"; } else { $message = 'No Leaderboard Table for this Index'; return new WP_ERROR('no_data', $message, array('status' => 404)); } if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close();
SQL - SELECT with WHERE statement return false despite present field in table
I am very confused about this (returning false): $sql = "SELECT * from tbl_user WHERE group = 'abc'"; $res = mysql_query($sql); if(mysql_num_rows($res) > 0) { $response = array('status' => '1'); } else { $response = array('status' => '0'); // ---> what I get back die("Query failed"); } ...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group: $SQL = "SELECT * FROM tbl_user"; $result = mysql_query($SQL); while ($db_field = mysql_fetch_assoc($result)) { print $db_field['group']; // ---> returns 'abc' When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing... This makes me mad. If anyone could help... (I am running a local server with MAMP). Thanks a lot!
The issue is that group is a reserved word in SQL. For MySql you need to escape it with backticks `group` So your query would be $sql = "SELECT * from tbl_user WHERE `group` = 'abc'";
MySQL - updating the average from one table into another table
I'm a MYSQL/PHP newbie and I'm sure this is a simple question. I'm trying to calculate the average of several questions and respondents from one table and updating a Group table with that value. For example Table answers consists of (name, group_id, TaskClarity1, TaskClarity2, TaskClarity3) in Table B i want (group_id, avg(TaskClarity1,TaskClarity2,TaskClarity3)). This is what I've got... $avg_task_clarity_1 = mysql_query("SELECT AVG(TaskClarity1) WHERE gruppid = '$group_id'"); $avg_task_clarity_2 = mysql_query("SELECT AVG(TaskClarity2) WHERE gruppid = '$group_id'"); $avg_task_clarity_3 = mysql_query("SELECT AVG(TaskClarity3) WHERE gruppid = '$group_id'"); $avg_task_clarity = ($avg_task_clarity_1+$avg_task_clarity_2+$avg_task_clarity_3)/3; $print_task_clarity_1" UPDATE results SET results.TaskClarity = '$avg_task_clarity'"; if (mysql_query($print_task_clarity_1)) { echo $print_task_clarity_1; } else { echo "Error TaskClarity1: " . mysql_error();
First, mysql_query() returns a resource, and you then need to extract information from it. Your query doesn't mantion any table name (I'll call it MyTable). Also, you can get all three averages with one query. Here's how I would start: $table = "MyTable"; $sql = "SELECT AVG(TaskClarity1) AS avgClarity1, AVG(TaskClarity2) AS avgClarity2, AVG(TaskClarity3) AS avgClarity1 FROM $table WHERE gruppid = '$group_id'"; $resource = mysql_query($sql); //execute the query if (! $resource = mysql_query($sql) ){ echo "Error reading from table $table"; die; } if (! mysql_num_rows($resource ) ){ echo "No records found in $table"; } else { $row = mysql_fetch_assoc($resource); // fetch the first row $avg_task_clarity_1 = $row['avgClarity1']; $avg_task_clarity_2 = $row['avgClarity2']; $avg_task_clarity_3 = $row['avgClarity3']; $avg_task_clarity = ($avg_task_clarity_1+$avg_task_clarity_2+$avg_task_clarity_3)/3; //... // other stuff you want to do } Please comment if this is not helpful enough, and I will revise my answer.
if specific row = null, execute query
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); } }