How to prevent null values to updating MySQL database - mysql

My update query is
"UPDATE registration SET `dob` = '".$theDate."' , pwd='".$_REQUEST['n_password']."', name='".$_REQUEST['n_name']."' where id='".$_SESSION['id']."' "
Problem is that it is not necessary that user update all fields so if it happens there are null values coming from form and it will replace earlier value in database.
I can update it one by one after checking if field value is not null but if there is any other way r tutorial please help me

I can update it one by one after checking if field value is not null
but if there is any other way r tutorial please help me
Don't issue an UPDATE query after you check each value, instead add that column to the query you're building, then execute just one UPDATE with only the columns that had values.
$dbh = new PDO('mysql:host=localhost;dbname=whatever', 'user', 'password');
$params = array();
$sql = "UPDATE REGISTRATION SET `dob` = ?";
$params[] = $theDate;
if (!empty($_REQUEST['n_password'])) {
$sql .= ", `pwd` = ?";
$params[] = $_REQUEST['n_password'];
}
if (!empty($_REQUEST['n_name'])) {
$sql .= ", `name` = ?";
$params[] = $_REQUEST['n_name'];
}
$sql .= " WHERE `id` = ?";
$params[] = $_SESSION['id'];
$stmt = $dbh->prepare($sql);
$stmt->execute($params);

Related

auto_increment not setting value for primary key?

I'm baffled, when I use the terminal (mysql) and insert into username,account_password columns, user_id AUTO_INCREMENTS just as it should.
my table:
CREATE TABLE users (
user_id int NOT NULL AUTO_INCREMENT,
user_type VARCHAR(20) NULL,
creation_date TIMESTAMP NOT NULL,
username VARCHAR(100) NOT NULL,
account_password VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
);
yet when I use this script:
use strict;
use warnings FATAL => 'all';# good for debugging, FATAL kills program so warnings are more identifiable
use CGI qw/:standard/;
use CGI::Carp qw(fatalsToBrowser); # good for debugging, sends info to browser
use DBI;
use DBD::mysql;
use Digest::SHA qw(sha256);
print header, start_html;
my $fName = param('firstName');
my $lName = param('lastName');
my $compName = param('compName');
my $email = param('email');
my $pswrd = param('password');
my $cnfPswrd = param('confPassword');
my $encpswrd = "";
#check passwords match, if not display error, and exit script
if ($pswrd eq $cnfPswrd) {
$encpswrd = sha256($pswrd);
} else {
print "Passwords did not match! refresh form!";
exit;
}
#database credentials, to be changed accordingly
my $database = "intsystest";
my $host = "localhost";
my $user = "root";
my $pw = "password";
my $dsn = "dbi:mysql:$database:localhost:3306";
#connect to database
my $dbh = DBI->connect($dsn, $user, $pw,
{ RaiseError => 1 }) or die "unable to connect:$DBI::errstr\n"; # <- this line good for debugging
#create, prepare, execute query, disconnect from DB
my $personsQuery = "INSERT INTO persons (first_name, last_name) VALUES (?,?)";
my $compQuery = "INSERT INTO company (company_name) VALUES (?)";
my $usersQuery = "INSERT INTO users (username, account_password) VALUES (?,?)";
my $sth = $dbh->prepare($personsQuery);
$sth->execute($fName, $lName);
$sth = $dbh->prepare($compQuery);
$sth->execute($compName);
$sth = $dbh->prepare($usersQuery);
$sth->execute($email, $encpswrd);
$dbh -> disconnect;
# additional processing as needed ...
print end_html;
I get this error:
DBD::mysql::st execute failed: Field 'user_id' doesn't have a default value at /usr/lib/cgi-bin/compSignUpDBCGI.pl line 44.
I'm assuming it's likely something wrong with the handler. What am I missing??
If your persons table has a foreign key to the users table then you need insert the users record first, then get the id of the new users record and add that to the SQL to insert the persons record.
Something like this:
my $usersQuery = "INSERT INTO users (username, account_password) VALUES (?,?)";
$sth = $dbh->prepare($usersQuery);
$sth->execute($email, $encpswrd);
$sth = $dbh->prepare('SELECT user_id FROM users WHERE username = ?');
$sth->execute($email);
my $user_id = $sth->fetch->[0];
my $personsQuery = "INSERT INTO persons (user_id ,first_name, last_name) VALUES (?,?,?)";
$sth = $dbh->prepare($personsQuery);
$sth->execute($user_id, $fName, $lName);
This is an area where DBIx::Class will definitely make your life easier.

Can't get a simple SELECT to work

I have done this type of SELECT many times, but this time I can't get it to work. Any ideas, please?
$Name = "Dick";
$conn = mysqli_connect($server, $dbname, $dbpw, $dbuser);
$sql = "SELECT id FROM table WHERE $Name = table.first_name";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$customer_id = $row['id'];
Database::disconnect();
echo "customer id = " . $customer_id;
If you really DO have a table named table it would be more appropriate to use back ticks around the name since the word TABLE is a reserved word in MySQL. You should also use single quotes around your variable if it contains a string:
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
Other possible reasons if the query still doesn't work for you:
Make sure you have the connection parameters in the right order. It should be: mysqli_connect($server, $dbuser, $dbpw, $dbname).
You should be using fetch_array() instead of fetch_assoc() if you expect a one row result.
You are mixing PROCEDURAL STYLE with Object Oriented Style when using mysqli_connect() instead of mysqli(), at the same time using $result-> which is object oriented style. You should decide one style and stick with it.
This would be the procedural style of your query:
$Name = "Dick";
$conn = mysqli_connect($server, $dbuser, $dbpw, $dbname); // NOTE THE CHANGED ORDER OF CONNECTION PARAMETERS!
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
mysqli_free_result($result); // FREE RESULT SET
mysqli_close($conn); // CLOSE CONNECTION
And this would be the object oriented style:
$Name = "Dick";
$conn = new mysqli($server, $dbuser, $dbpw, $dbname);
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = $conn->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
$result->free(); // FREE RESULT SET
$conn->close(); // CLOSE CONNECTION
I would recommend naming your table something else than table since it's a reserved word and could get you into parsing problems. The same goes with field names. More reading: https://dev.mysql.com/doc/refman/5.5/en/keywords.html
More about mysqli_fetch_array() and differences in procedural style and object oriented style use: http://php.net/manual/en/mysqli-result.fetch-array.php
$sql = "SELECT id FROM table WHERE '$Name' = table.first_name";
You simply need to concat the variable like this:
$sql = "SELECT id FROM table WHERE " . $Name . " = table.first_name";

SELECT * FROM WHERE Query isn't retrieving any results

I'm using a SELECT * FROM "" WHERE "" = "" query and I'm not sure what I'm doing wrong with it. I'm trying to select an item based on its PO which is a completely unique identifier to one row in the table. Here's my process in doing so:
$jobnumber = $_GET['jref'];
$query = "SELECT * FROM `po_10152796` WHERE `po` = " .$jobnumber;
$results = mysqli_query($conn,$query) or die(mysqli_error($conn));
$rowitem = mysqli_fetch_array($results);
$jobname = $rowitem['Job Name'];
$phone = $rowitem['phone'];
Things i know are correct:
The "jobnumber" is retrieved correctly and matches up with an element in the table
The table is named "po_10152796" and there is a column named "po"
Forgot to post this, redid the code with prepared statements and it works, not sure what exactly I changed but here it is anyhow:
$jobnumber = $_GET['jref'];
$stmt = $conn->prepare( "SELECT `Job Name`, `Address`, `phone`, `description`, `materials` FROM po_10152796 WHERE po = ?");
$stmt->bind_param("i", $jobnumber);
if($stmt->execute()){
$stmt->bind_result($jobname, $address, $phone, $description, $materials);
$stmt->fetch();
}
try this line for the query
$query = "SELECT * FROM `po_10152796` WHERE `po` = '" .$jobnumber. "' ";

SQL update not committed

I am having a weird issue but I do not understand what is happening. I amcreated a function to update up to three columns (end_plan_date, balance and server) in a table (user) and 2 inserts in another table.
For some reason, my last update (column server of the user table) is not committed ($query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");) unless I give a value for at leat one of the two other values ($subamt or $subday).
Do you know why this query is not updating the user table with the server value I parsed?
function addBalance($subemail, $subamt,$subday,$userid,$serv) {
$q = "SELECT * FROM user WHERE email = '$subemail'";
$result = mysql_query($q, $this->connection);
$dbarray = mysql_fetch_array($result);
$endplan_date=$dbarray['end_plan_date'];
if($subday >0){
if($endplan_date=="0000-00-00" ){
$endplan_date = date('Y-m-d');
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}else{
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}
$query = mysql_query("UPDATE user SET end_plan_date='$new_endplan_date' WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES ('$recdate','$userid','Plan Date','$subday')";
mysql_query($q, $this->connection);
}
if($subamt >0){
$query = mysql_query("UPDATE user SET balance=balance+".$subamt." WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES '$recdate','$userid','Balance','$subamt')";
mysql_query($q, $this->connection);
}
$query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");
return 0;
}
In your code u can't get directly this
$endplan_date=$dbarray['end_plan_date'];
for fetching this variable u have to use while loop like
while($dbarray = mysql_fetch_array($result);) {
$endplan_date=$dbarray['end_plan_date'];
}
There was an issue when calling this function.

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