How to get array difference in php using arrays with two elements - php

So, I have two queries which will pull out data from the database. However, I need to use these data to get the array difference by using php. I want to send both employeeName and designation into an array and then get the difference. The below code I have used does not work as expected. Any solution for this matter ?
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include_once 'config.php';
$sql1 = "SELECT employeeName, designation FROM t2o_mappings WHERE type = '". $_GET['type'] ."' AND employeeCompany = '".$_GET['employeeCompany']."'"; //System Data;
$sql2 = "SELECT employeeName, designation FROM mappings_view WHERE uNo = '" . $_GET['uNo'] . "' AND uCompany = '" . $_GET['uCompany'] . "' AND type = '". $_GET['type'] ."' AND employeeCompany = '".$_GET['employeeCompany']."'"; //App Data;
//WHERE uNo = '".$_GET['uNo']."' AND uCompany = '".$_GET['uCompany']."'
$result1 = sqlsrv_query($conn, $sql1);
$result2 = sqlsrv_query($conn, $sql2);
$row1 = [];
$row2 = [];
while ($rs1 = sqlsrv_fetch_array($result1, SQLSRV_FETCH_ASSOC)) {
$row1[] = $rs1['employeeName, designation'];
}
while ($rs2 = sqlsrv_fetch_array($result2, SQLSRV_FETCH_ASSOC)) {
$row2[] = $rs2['employeeName, designation'];
}
print_r($row1);
print_r($row2);
$HaveSysNoApp = array_diff($row1, $row2); //Have in System, Not in App
$HaveAppNoSys = array_diff($row2, $row1); //Have in App, Not in System
echo 'HaveSysNoApp';
print_r($HaveSysNoApp);
echo '$HaveAppNoSys';
print_r($HaveAppNoSys);
?>

You have a syntax problem here
$row1[] = $rs1['employeeName, designation'];
The right way would be :
$row1[] = [
$rs1['employeeName'],
$rs1['designation']
];
But array_diff() throws the notice "array to string conversion" because it can only deals with one dimension. The PHP array_diff() documentation contains this note :
Note:
Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In other words: when the string representation is the same.
Since you have multidimensional arrays to compare, you could use the array_filter() function.
For example :
$HaveSysNoApp = array_filter($row1, function ($item) use ($row2) {
return !in_array($item, $row2);
});

You could do it directly in database with this query (the opposite check would be similar):
SELECT system.employeeName, system.designation
FROM t2o_mappings AS system
WHERE system.type = ?
AND system.employeeCompany = ?
AND NOT EXISTS (
SELECT NULL
FROM mappings_view AS app
WHERE app.employeeName = system.employeeName
AND app.designation = system.designation
AND app.type = system.type
AND app.uNo = ?
AND app.uCompany = ?
)
These question marks make it parametrized query, wich prevents SQL injection (parameter values are not part of the query, so they can't change its meaning). You would call it with additional parameter array (order must match):
$params = [
$_GET['type'],
$_GET['employeeCompany'],
$_GET['uNo'],
$_GET['uCompany']
];
$haveSysNoAppResult = sqlsrv_query($conn, $sql, $params);

Related

PHP Creating variables list from Mysql database

I've a database that using for 3 languages this way:
id name de_de al_sq
1 title titel titulli
2 points punkte pike
Now when in php $lang is set to 'al_sq':
$lang = 'al_sq';
I'm trying to generate variables using names of that language, in this case:
$langtitle = 'titulli';
$langpoints = 'pike';
Trying something like:
$sql = "SELECT * FROM `langs`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$lang{$row["lang"]} = $row[$lang];
}
}
but something is not good, how to generate these variables?
You have a minor syntax error in your code, which causes an error. What you need to do here is to:
Fetch the name and al_sq columns from the database table. This is done by selecting the value of $lang (based on your code). For security reasons, the value of $lang is protected against SQL injection, as you did not specify where the value was coming from.
Then you must check if there was any results, and in the case there wasn't any, it will simply terminate the script with an error.
Then lastly you must iterate over each row of the returned results, and do a variable variable assignment. This will make $langpoints etc. work (and any other you may add in the future).
Code:
$sql = 'SELECT `name`, `' . $conn->real_escape_string($lang) . '` FROM `langs`';
$result = $conn->query($sql);
if (!$result || !$result->num_rows) {
echo 'Invalid language selected';
exit;
}
while ($phrase = $result->fetch_assoc()) {
${'lang' . $phrase['name']} = $phrase[$lang];
}
// $langtitle
// $langpoints
It seems you are using the database as a key-value store with multiple value fields depending on the language, you could use PDO::FETCH_KEY_PAIR so it returns an array with the name as the key. This way you also avoid loading the data for other languages that you might not need at all:
$query = "SELECT `name`, :column as value FROM `langs`";
$statement = $pdo->prepare($query);
$statement->execute(["column" => $lang]);
$data = $statement->fetchAll(\PDO::FETCH_KEY_PAIR);
// $data becomes an array with the name as the key:
$langtitle = $data['title'];
$langpoints = $data['points'];
Make sure, if the user provides the value for $lang, to check that it is a valid column value.
This should be close to what you are wanting based on how your database is presented. Scaling up would be clunky though if there is more the title and points stored.
$lang = 'al_sq';
$sql = "SELECT $lang FROM 'langs'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$langtitle = $row[1];
$langpoints = $row[2];
}
}

Explode array from mysql and assign to variables PHP

OK so in the database I have a column that contains data like this
:Novice:Intermediate:Advanced
( some columns have more than the 3 listed above )
What I'm trying to do is explode at the : and then assign the exploded values to variables
At most there are 4 bits of data separated by : so a max of 4 variables
Here is the code I have so far
$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);
do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>'.$var4;
}while($result = mysql_fetch_assoc($query));
It works ( to an extent )
For example record ID 13 has this in the column
:Novice:Novice/Intermediate:Intermediate/Advanced:Advanced:
The output however does NOT display the final
Advanced
it only displays
Novice
Novice/Intermediate
Intermediate/Advanced
Anyone help me please I am pulling hair out badly here .
I have also tried adding another $var5 but that doesnt help
I forgot to add $var5 to the list()
$query = mysql_query("SELECT * FROM venues WHERE id ='30'",$dbc);
$result = mysql_fetch_assoc($query);
do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4,$var5) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>'.$var4.'<br>'.$var5;
}while($result = mysql_fetch_assoc($query));
Working fine now :)
do it like this
$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);
$i=0;
while($result = mysql_fetch_assoc($query)){
$var1[$i]=$row['Novice'];
$var2[$i]=$row['Intermediate'];
$var3[$i]=$row['Advanced '];
echo $var1[$i].'<br>'.$var2[$i].'<br>'.$var3[$i].'<br>';
$i++;
}
Your problem it´s how you are trying to get the values from the table and explode.
I use something like this:
$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)) {
$def_sessions = row(number of yor row);
$eventtype = explode(":", def_sessions);
$val0 = $eventtype[0];
$val1 = $eventtype[1];
...
}

How do I re-write this SQL statement to accept the array variable?

I am making an API call to retrieve user_name's from my database.
My first step is to make a call to retrieve all the player_id's. They are stored in $communityPlayersIds and currently output as below:
["2","31","31","32"]
I now want to make a second call to the database to fetch the user_name's of the id's that match.
$communityPlayerNames = array();
$communityPlayerNames = $dao->getPlayerNames($communityPlayersIds);
I have looked into it and seen I should use an IN command something like this:
public function getPlayerNames($player_ids)
{
$returnValue = array();
$sql = "SELECT user_name\n"
. "FROM users\n"
. "WHERE id IN ( '".$player_ids."')";
$result = $this->conn->query($sql);
if($result != null && (mysqli_num_rows($result) >= 1)){
while($row = $result -> fetch_array(MYSQLI_ASSOC)){
if(!empty($row)){
$returnValue[] = $row;
}
}
}
return $returnValue;
}
}
However this isn't working and returns this:
[{"user_name":null}]
If I echo ($sql) I get this:
SELECT user_name FROM users WHERE id IN ( '2,31,31,32')
Which looks correct does it not?
Where am I going wrong?
You essentially want your final query to look like this
Select user_name from users where id in (2,31,31,32) -- dupe 31 does no harm
Make sure your series of IDs are inside parentheses IN ($player_ids) and not just a single quote IN '$player_ids'
You can try building the IN-part of the SQL like this:
$returnValue = array();
$in_statement = "(";
foreach($player_ids as $player_id)
{
$in_statement = $in_statement.$player_id->player_id.",";
}
rtrim($in_statement, ",");
$in_statement = $in_statement.")";
$sql = "SELECT community_players.player_id\n"
. "from community_players\n"
. "where community_players.community_id in ".$in_statement."";
So just the middle-part is new, where the $in_statement gets build. And in your SQL you have to change the "=" to "IN". You can generate the IN-part shorter, but this way you can easier see how it's done, so you can fit it to your needs.
in your code you put ' after in which shows syntax error.
You can try
Assuming your
$communityPlayersIds has below value as array:
["2","31","31","32"]
if its not an array then convert it using json_decode()
and then try below query
$sql = "SELECT community_players.player_id\n"
. "from community_players\n"
. "where community_players.community_id IN (".join(",",$communityPlayersIds).")";

array_sum returning the sum of values as string

This seems like it should be really straightforward, but I keep getting unexpected output. I'm trying to access specified rows in a SQL database which each contain a numerical value and then calculate the sum of those values. PHP is concatenating the values as if they were strings even after I've set the datatype of the values to float. My code:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
$population_value = is_array($population_value) ? $population_value : array($population_value);
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I have also tried:
$total = array("");
foreach($population_value as $value){
floatval($value);
array_push($total, $value);
echo $value;
}
echo array_sum($total);
My output is always something like: 100002000030000
with 10,000 20,000 and 30,000 being the values of each population.
I've successfully calculated sums using foreach with values that weren't retrieved from MySQL.
What is going on here?
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
//This is actually rewriting the array or NOT adding the value to it.
$population_value = is_array($population_value) ? $population_value : array($population_value);
//ok, so you're going to repeatedly output this?
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I think what you want is this:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
$population_value=array(); //Initialize the array so we can just add to it.
while($row = mysqli_fetch_assoc($result)) {
$population_value[]= intval($row['population_value']); //Just making sure we get a number.
echo end($population_value); //We could output the row again, or just grab the last element of the array we added.
}
//Now that the array is fully populated and we've made sure it's only numbers, we output the grand total.
echo array_sum($population_value);
First, don't initialize the array with an empty string. Do this instead:
$total = array();
or with the new style:
$total = [ ];
Second, rewrite the floatval thing like this:
array_push($total, floatval($value));
That should fix it...

Update Every row in MYSQL with Unique Value

I'm trying to assign a field called 'uniqueid' to each row present in my database. There are roughly 188,000 rows available.
Here is the code I am using:
$connection = mysql_connect("localhost","root","root");
mysql_select_db("comics",$connection) or die ("Database not found");
$query = mysql_query("select * from comic_issues");
if ($query){
$rows = mysql_num_rows($query);
foreach($rows as $row){
$str = strtolower($row['series'].$row['volume'].$row['issue']);
$str = preg_replace('/[^A-Za-z0-9]/', '', $str);
$update = "update comic_issues set uniqueid='" . $str . "' where id='" . $row['ID'] . "'";
mysql_query($update);
exit();
}
}
What is happening is that every row gets updated with the same uniqueid, which seems to be a different value each time I run the script.
Instead of
foreach($rows as $row){
you need to do
while ($row = mysql_fetch_row($query)) {
In your code $rows is a number and not an array, therefore you can't do a foreach on it.
Just let MySQL do it all for you:
UPDATE comic_issues SET uniqueid = LOWER(CONCAT(series,volume,issue))
If you must also strip all non-alphanumeric characters, you can either write a stored function or else use a UDF.

Categories