Converting empty string into null - mysql

I have a form that POST value keeps coming as "" empty string into a unique SQL field.
It has to be unique as the field is optional but jet it can not have 2 same values. The unique value does allow null multiple values.
I don't even want to say what I tried to do, I'm trying to fix this for last few days.
Closest that I got is putting '$OIB'=IF('$OIB'='',NULL,'$OIB' into NSERT INTO statement, then i get null values into a database but for some reason when the number is entered into OIB form field it puts number 1 into a database...
$result = mysqli_query($conn, "SELECT OIB, NAZIV FROM STRANKEP WHERE OIB = '$OIB' OR NAZIV = '$NAZIV'");
if(mysqli_num_rows($result) == 0) {
// row not found, do stuff...
$sql = "INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES ('$NAZIV', CASE WHEN '$OIB' = '' THEN 'NULL', '$EMAIL', '$ADRESA', '$TELEFON')";
$query = mysqli_query($conn, $sql);
This solution gets me null but not the real $OIB when entered into form, it just puts number 1.
$result = mysqli_query($conn, "SELECT OIB, NAZIV FROM STRANKEP WHERE OIB = '$OIB' OR NAZIV = '$NAZIV'");
if(mysqli_num_rows($result) == 0) {
// row not found, do stuff...
$sql = "INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES ('$NAZIV', '$OIB'=IF('$OIB'='',NULL,'$OIB'), '$EMAIL', '$ADRESA', '$TELEFON')";
$query = mysqli_query($conn, $sql);
Thank you in advance for the help.

Try
CASE '$OIB' WHEN '' THEN NULL ELSE '$OIB' END

You can use also IF Clause
Like so
INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES
('$NAZIV', IF('$OIB' = '', NULL,'$OIB'), '$EMAIL', '$ADRESA', '$TELEFON');
But as mentioned in my comment use prepared statements like in PDO https://phpdelusions.net/pdo#prepared

I would recommend nullif(). It is a built-in standard function to do exactly this:
nullif(?, '')
Note: Do not munge queries with constant values. That makes the code subject to SQL injection attacks. And it can introduce very hard-to-debug errors. Use parameters!

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();
?>

Updating Multiple Column on MySQL

I want to update members_roosevelt table ACCOUNT column starting with 3000+ value I also want to update ACCOUNT column on loan_roosevelt table that is related to my member_roosevelt. What's wrong with my query? Thank you!
$query1 = "SELECT ACCOUNT
FROM
`members_roosevelt`";
$result_q1 = $link->query($query1) or die($link->error);
while ($obj = $result_q1->fetch_object()) {
$members[] = $obj->ACCOUNT;
}
$ids = implode(',', $members);
$sql = "UPDATE `members_roosevelt` as `memb`
JOIN `loan_roosevelt` as `loan`
ON `memb`.`ACCOUNT` = `loan`.`ACCOUNT`
SET
(`memb`.`ACCOUNT`,
`loan`.`ACCOUNT`) = CASE ACCOUNT";
foreach ($members as $id => $ordinal) {
$sql .= sprintf("WHEN %d THEN %d ", $ordinal, (3000+$id));
}
$sql .= "END WHERE memb.ACCOUNT IN ($ids)";
$link->query($sql) or die($link->error);
SET (`memb`.`ACCOUNT`, `loan`.`ACCOUNT`) = CASE ACCOUNT...
This is simply not part of SQL syntax. You can't set two columns at a time like this. The left side of an assignment operator must be one column.
A better solution is to use a session variable.
SET #acct = 3000;
UPDATE members_roosevelt as memb
JOIN loan_roosevelt as loan
ON memb.ACCOUNT = loan.ACCOUNT
SET memb.ACCOUNT = (#acct:=#acct+1),
loan.ACCOUNT = (#acct);
This way you don't have to run the SELECT query at all, and you don't have to create a huge UPDATE statement with potentially thousands of WHEN clauses.
Demo: SQLFiddle

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'";

update enum value from 1 to 0 mysql?

i'm trying to get this script to update my enum column 'read_message' in my 'ptb_messages' table but it just doesn't do anything. the rest of the script works fine but it's just ignoring the request to update 'read_message from 1 to 0.
can someone please show me where im going wrong? thanks
<?php
session_start();
include 'includes/_config/connection.php';
$subject = $_POST['subject'];
$message_id=$_GET['to'];
$textarea = $_POST['textarea'];
$query = mysql_query("SELECT content FROM ptb_messages WHERE id='".$message_id."'");
$results=mysql_fetch_array($query);
$result=$results['0'];
if($result && $textarea) {
$sql = mysql_query("UPDATE ptb_messages SET content ='".addslashes($textarea)."' WHERE id='".$message_id."'");
$sql = mysql_query("UPDATE ptb_messages SET date_sent = LOCALTIME WHERE id='".$message_id."'");
$query = mysql_query("SELECT suibject FROM ptb_messages WHERE id='".$message_id."'");
$sql = mysql_query("UPDATE ptb_messages SET subject = IF(subject LIKE '%:reply', subject, CONCAT(subject, ':reply')) WHERE id='".$message_id."'");
$sql = mysql_query("UPDATE ptb_messages SET read_message = '0' WHERE id=".$message_id."");
$_SESSION['message_sent']="<div class=\"message_sent\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}#confirm");
}
?>
You're hitting an edge case in MySQL. enum fields can have their values to referred to by the actual value, or their INDEX in the list of allowable values. You're trying to use 0, which MySQL is interpreting as index 0 of the list, which internally is the empty string.
e.g.
myfield ENUM('one', 'two', 'three')
myfield = 'two' => 'two'
myfield = 1 => 'one'
myfield = 0 => '', not in list, ignore...
If you just need a 0/1 value for a field, why not use an actual BIT field, which is already 0/1/null-only? Using enums for purely numeric values just runs into this value-v.s.-index problem.

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']
";