how i insert 1 data with 2 string? and insert into database? - mysql

i was doing a insert statement and i want 2 username become 1 data and insert into database. i no sure how to do it.
here is my php and mysql
$target = $_GET['user'];
$id = $_SESSION['id'];
$targetusername = mysqli_query($connection,"SELECT username FROM user WHERE id='$target' ")or die(mysqli_error($connection));
$username= mysqli_query($connection,"SELECT username FROM user WHERE id='$id'") or die(mysqli_error($connection));
$direct_message_room_name ="INSERT INTO direct_message_room(`direct_message_room_name`,`user_1_id`,`user_2_id`) VALUES (('$targetusername' + ' and ' + '$username'),'$id','$target')";

In order to have two variables in one column, you can serialize an array, though this is generally frowned upon unless it's for a good reason.
$array = array('username'=>'user1','username2'=>'user2');
$serialize = serialize($array);
Gives you:
a:2:{s:8:"username";s:5:"user1";s:9:"username2";s:5:"user2";}
Use the unserialize() function to return it to an array. Wordpress is one notable web application that stores arrays in such a way.
On a side note, you need to use bind parameter to avoid injectable sql queries:
// Do not do this
$target = $_GET['user'];
mysqli_query($connection,"SELECT username FROM user WHERE id='$target' ")
Here is a reference:
What does bind_param accomplish?

You can concat two strings in php like so:
$StringAB = $StringA . " something " . $StringB;
$target = $_GET['user'];
$id = $_SESSION['id'];
$targetusername = mysqli_query($connection,"SELECT username FROM user WHERE id='$target' ")or die(mysqli_error($connection));
$username= mysqli_query($connection,"SELECT username FROM user WHERE id='$id'") or die(mysqli_error($connection));
$rowUserName = mysql_fetch_array($username);
$rowTargetUserName = mysql_fetch_array($targetusername );
$room_name = $rowUserName["username"] . ' and ' . $rowTargetUserName["username"]; // Create room name (assuming both exist)
$direct_message_room_name ="INSERT INTO direct_message_room(`direct_message_room_name`,`user_1_id`,`user_2_id`) VALUES ('$room_name','$id','$target')";

Related

Add 2 numbers together, one from a database result and the other from post array

I'm trying to add 2 numbers together. The first number is from the database say it's 150 it comes from the $sql1 and the second number comes from the form and is in the POST array say it's 25. Once the $sql2 is run the number in the database should be 175 but it's still 150, any ideas on what i'm missing/doing wrong?
$sql1 = "SELECT points FROM users WHERE userID = ?";
$qc1 = $pdo_conn->prepare($sql1);
$qc1->execute(array($_POST['userID']));
$result = $qc1->fetch(PDO::FETCH_ASSOC);
$points = $result + $_POST['addPoints'];
$sql2 = "UPDATE users SET points = ? WHERE userID = ?";
$qc2 = $pdo_conn->prepare($sql2);
$qc2->execute(array($points, $_POST['userID']));
Based on your code, the $result variable is going to return the response from the database as an array. Thus, in order to get the number, you need to pass the field name from your SELECT statement.
Therefore,
$points = $result + $_POST['addPoints'];
should be:
$points = $result['points'] + $_POST['addPoints'];

SQL Insert/Update does fails, does not invoke errors

Afternoon everyone,
I'm currently trying to insert or update form field values via params into a mysql after some simple validation. The form submits, but does not actually execute any of the operations and does not raise a syntax or database connection error. I know my connection string works because I fetched values from it to compare to in the code prior to the nested evaluation blocks shown below. The foreach loops were inserted as an alternate means of validating that the values have indeed been altered in the table. Your help is greatly appreciated, as always:
my $dbusr = param("dbuser");
my $dbpw = param("dbpass");
my $dbmail = param("dbemail");
my $dbtel = param("dbphone");
my $postflag = param("Submit");
if ($dbusr ne "") {
$sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
$sth->execute('$dbusr');
warn( $DBI::errstr ) if ( $DBI::err );
my #results = $sth->fetchall_arrayref();
foreach(#results){
if ($dbusr eq $_){
$loopval = 1;
}
}
unless($loopval){
$sth = $dbh->prepare("INSERT INTO USER
(username, password, phone, email)
values
(?,?,?,?)");
$sth->execute($dbusr, $dbpw, $dbtel, $dbmail);
warn( $DBI::errstr ) if ( $DBI::err );
$sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
$sth->execute('$dbusr');
#results = $sth->fetchall_arrayref();
foreach(#results){
if ($dbusr eq $_){
$successflag = 1;
}
}
}
else{
$sth = $dbh->prepare("UPDATE USER
SET (password = ?, phone = ?, email = ?)
WHERE username = ?");
$sth->execute($dbpw, $dbtel, $dbmail, $dbusr);
warn( $DBI::errstr ) if ( $DBI::err );
$sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
$sth->execute('$dbusr');
#results = $sth->fetchall_arrayref();
foreach(#results){
if ($dbusr eq $_){
$successflag = 1;
}
}
}
}
Basic Perl: '-quoted strings do NOT interpolate variables:
$sth->execute('$dbusr');
^-- ^---
You're literally passing $, d, b, etc... to your query as the placeholder value.
Try
$sth->execute($dbusr); // note the lack of ' quotes
instead.
You are searching for entire rows with the SELECT * FROM USER WHERE username LIKE ? statement, and are then fetching all the rows in one go with
my #results = $sth->fetchall_arrayref();
That method "returns a reference to an array that contains one reference per row.", but you are treating the returned value as an list of usernames:
foreach(#results){
if ($dbusr eq $_){
$loopval = 1;
}
}
To make this work you should just fetch the username column, and treat the returned rows as references of references. And as you look for exact matches in the database replace LIKE with =:
$sth = $dbh->prepare("SELECT username FROM USER WHERE username = ?");
$sth->execute($dbusr); # no quoting
die( $DBI::errstr ) if ( $DBI::err ); # what else to do if the execute fails?
my $results = $sth->fetchall_arrayref(); # an arrayref is returned
foreach(#$results){ # de-reference the array
if ($dbusr eq $_->[0]){ # each row is an arrayref, look in first element
$loopval = 1;
}
}
(Of course the same applies to the second search.)

MYSQL query with variables that may not be set

I have a PHP file which is taking in seven variables like so:
$name=$_REQUEST['membername'];
$email=$_REQUEST['email'];
$dob=$_REQUEST['dob'];
$gender=$_REQUEST['gender'];
$phone=$_REQUEST['phone'];
$county=$_REQUEST['county'];
$IP=$_REQUEST['IP'];
Some of these will not be set. What I want to do is construct a query which will search the members table such that if only $email and $dob are set it will only search by $email and $dob, ignoring the others. Or if only $phone, $name, and $gender are set, it will search those three columns only.
Is there an easier method than constructing a big block of if isset functions covering all possible permutations?
If you don't want to search on a field, pass NULL for the parameter and structure your WHERE clause something like...
WHERE
( (#parameter1 IS NULL) OR (column1 = #parameter1) )
AND
( (#parameter2 IS NULL) OR (column2 = #parameter2) )
I don't spend much time in MYSQL so the syntax is probably a bit off but you get the idea.
Presuming that you use parameters to push values into the query...
SELECT *
FROM MyTable
WHERE name = COALESCE(#p1, name)
OR email = COALESCE(#p2, email)
OR dob = COALESCE(#p3, dob)
...
...
If you construct a query string in PHP you can, instead, take another tack:
function AddWhere(&$where, $dbFieldName, $fieldValue)
{
if ($fieldValue <> "")
{
if (strlen($fieldName) > 0)
$fieldName .= " AND ";
$fieldname .= '(' + $dbFieldName + ' = \'' + $fieldValue + '\')'
}
}
Then, when you're retrived the variables, build a SQL statement thusly
$whereClause = ''
AddWhere($whereClause, 'name', $name)
AddWhere($whereClause, 'email', $email)
AddWhere($whereClause, 'dob', $dob)
...
IF (strlen($whereClause) > 0)
{
$sql = 'SELECT * FROM MyTable WHERE ' + $whereClause
... etc
}
(I'm not great at PHP, so the syntax may be somewhat screwed up).

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

Trouble updating a particular user in a mysql database

im trying to update a particular user that is logged in using UPDATE mysql command, but instead it is going to the first user that is in the database itself, if you can help id appreciate it
Edit: Im wanting to increment the number of 'items' that a user has, but for the code below its only going to the first user in the database
<?php
session_start();
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$dbname = '';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die ('Error connecting to mysql');
mysql_select_db($dbname);
$query = sprintf("UPDATE users SET item = item + 1 ",
mysql_real_escape_string($_POST['item']));
mysql_query($query);
?>
Your sprintf() call has a parameter, but no placeholder:
$query = sprintf("UPDATE users SET item = item + 1 ",
mysql_real_escape_string($_POST['item']));
Probably this is supposed to be something like the following, assuming an INT column named item
$query = sprintf("UPDATE users SET item = item + 1 WHERE item = %d ",
mysql_real_escape_string($_POST['item']));
UPDATE
If you are trying to target a specific user only, then you need that user's id or username in $_POST instead of item. You'll need to post the output of var_dump($_POST) for us to see just what values you've received in post.
Assuming a string username, use:
$query = sprintf("UPDATE users SET item = item + 1 WHERE username = '%s' ",
mysql_real_escape_string($_POST['username']));
you need some kind of where clause. specify which user you want to actually update with extra conditions.
YOu need to know which user you want to update...
$query = sprintf("UPDATE users SET item = item + 1 WHERE userId="+ $userId,
or something like that...