Compare multiple values in two arrays PHP - php

I have two MySQL Databases, and would like to compare the data using PHP variables. I connect to the databases and assign the variables using PDO:
//Database 1
include_once('client-config.php');
try {
$conn = new PDO(DB_HOST, DB_USER, DB_PASSWORD, array(PDO::ATTR_PERSISTENT => TRUE));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$DB_Name = "pencuy204";
$login = $_SESSION['SESS_login'];
$qry = "SELECT `BetType`, `RiskAmount`, `WinAmount`, `BetDate`, `GameDate`, `BetRotation`, `TeamParticipant`, `MoneyLine`, `Spread`, `OverUnder`
FROM `{$login}_bet`";
$result = $conn->query($qry);
// If the SQL query is succesfully performed ($result not false)
if ($result !== false) {
// Parse the result set, and adds each row and colums in HTML table
foreach ($result as $row) {
$BetType[] = $row['BetType'];
$BetRiskAmount[] = $row['RiskAmount'];
$BetWinAmount[] = $row['WinAmount'];
$BetGameDate[] = strtotime($row['GameDate']);
$BetTeamParticipant[] = $row['TeamParticipant'];
$BetMoneyLine[] = $row['MoneyLine'];
$BetSpread[] = $row['Spread'];
$BetOverUnder[] = $row['OverUnder'];
}
}
//Database 2
try {
require_once('bet-config.php');
$conn1 = new PDO(B_DB_HOST, B_DB_USER, B_DB_PASSWORD);
$conn1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
date_default_timezone_set('CST');
$today = date("Y-m-d");
$qry = "SELECT `AwayTeam`, `AwayScore`, `HomeTeam`, `HomeScore`, `FeedDate` FROM games";
$checkit = $conn1->query($qry);
if ($checkit !== false) {
foreach($checkit as $row1) {
$AwayTeam[] = $row1['AwayTeam'];
$HomeTeam[] = $row1['HomeTeam'];
$AwayScoreData[] = $row1['AwayScore'];
$HomeScoreData[] = $row1['HomeScore'];
$FeedDate[] = strtotime($row1['FeedDate']);
}
}
What I would like to do is run through each value in certain PHP arrays in Database 1, comparing them every value in certain arrays in Database 2. Here is an example for loop that I am working on:
for ($i = 0; $i <= $count; $i++) {
foreach ($BetGameDate as $b) {
if (($b == $FeedDate[$i])) {
foreach ($BetTeamParticipant as $team) {
if (($team == $AwayTeam[$i])) {
foreach ($BetType as $type) {
if (($type == "Money Line")) {
if ($AwayScoreData[$i] < $HomeScoreData[$i]) {
$BetV[] = "-" . $BetRiskAmount[$i];
$BetC[] = intval('$BetV');
}
if ($AwayScoreData[$i] > $HomeScoreData[$i]) {
$BetV[] = "+" . $BetWinAmount[$i];
$BetC[] = intval('$BetV');
}
if ($AwayScoreData[$i] == $HomeScoreData[$i]) {
$BetV[] = 0;
$BetC[] = intval('$BetV');
}
}
}
}
}
}
}
}
In this particular example, if $GameBetDate is equal to $FeedDate, the bet team name is equal to the away team name, and the bet type is equal to a certain string, then compute the bet based on the risk amount or win amount for that specific bet(row) in database 1. I feel like my use of foreach is correct, but how can I properly use an iterated for loop to cycle through all of the values in database 2 against the specific values in database 1, and if the criteria matches, use values from database 1 to calculate $BetC and BetV?

I think you can use a little refactoring in your code.
To compare values you can use array_diff method.
You select the values from the first table, (PDO can return array)
Select second values and compare...
http://php.net/manual/en/function.array-diff.php

Related

How to search for string in array in PHP?

so i got this big xml which can be found at here and i store in my database as settype-setId-partId and i want to filter unknown strings and replace them.Here's what i tried:
<?php
try {
$conn = new PDO("mysql:host=localhost;dbname=db", "root", "");
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$figuredata = simplexml_load_file("figuredata.xml");
$users = $conn->prepare("SELECT figure, username from players");
$users->execute();
$users = $users->fetchAll(PDO::FETCH_OBJ);
foreach($figuredata->sets->settype as $settype) {
foreach($settype->set as $set) {
foreach($set->part as $part) {
foreach($users as $user ) {
$lookArr = explode(".",$user->figure);
foreach($lookArr as $look ){
$lookArrNew = explode("-", $look);
if($lookArrNew[1] != $set->attributes()->id && $lookArrNew[2] != $part->attributes()->id) {
echo "fail";
}
}
}
}
}
}
But it returns fail for every string. What should I do?
If you use XPath to search for the data rather than having all of the various loops, you can reduce the code to reading in the players and then searching for the entry.
This uses an XPath expression //set[#id="'.$lookArr[1].'"]/part[#id="'.$lookArr[2].'"], which will look for something like //set[#id="3774"]/part[#id="3329"]. This is a <set> value with an attribute value for id = 3774, which has a <part> with an id attribute of 3329.
xpath() returns a list, so if it's empty the value isn't found.
$users = $users->fetchAll(PDO::FETCH_OBJ);
foreach($users as $user ) {
$lookArr = explode(".",$user->figure);
foreach($lookArr as $look ){
$lookArr = explode("-",$figure);
$set = $figuredata->xpath('//set[#id="'.$lookArr[1].'"]/part[#id="'.$lookArr[2].'"]');
if ( empty($set) ) {
echo "fail";
}
else {
echo $set[0]->asXML();
}
}
}

creating new db rows from data in array?

Hey guys im trying to pass some data from an (oracle) fetch_array to a variable array and then use that array data to check if the data exists on a mysql db and create any rows that dont currently exist.. this is what i have so far.
the problem is its only checks/creates 1 entry of the array and doesn't check/created the entire array data. i think i would need to use a for loop to process all the array data concurrently
<?php
$conn = oci_connect('asdsdfsf');
$req_number = array();
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, " SELECT WR.REQST_NO
FROM DEE_PRD.WORK_REQST WR
WHERE WR.WORK_REQST_STATUS_CD = 'PLAN' AND WR.DEPT_CD ='ISNG'
");
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
// Use the uppercase column names for the associative array indices
$req_number[]= $row['REQST_NO'];
}
oci_free_statement($stid);
oci_close($conn);
//MYSQL
//Connection Variables
//connect to MYSQL
$con = mysqli_connect($servername,$username,$password,$dbname);
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
// lets check if this site already exists in DB
$result = mysqli_query($con,"
SELECT EXISTS(SELECT 1 FROM wr_info WHERE REQST_NO = '$req_number') AS mycheck;
");
while($row = mysqli_fetch_array($result))
{
if ($row['mycheck'] == "0") // IF site doesnt exists lets add it to the MYSQL DB
{
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
if (mysqli_query($con, $sql)) {
$created = $req_number." Site Created Successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}else{ // if site is there lets get some variables if they are present...
$result = mysqli_query($con,"
SELECT *
FROM wr_info
WHERE REQST_NO = '$req_number[0]'
");
while($row = mysqli_fetch_array($result))
{
$do some stuff
}
}
}
mysqli_close($con);
?>
You create an array:
$req_number = array();
And loop over records to assign values to the array:
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
$req_number[]= $row['REQST_NO'];
}
But then never loop over that array. Instead, you're only referencing the first record in the array:
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
// etc.
(Note: There are a couple of places where you directly reference the array itself ($req_number) instead of the element in the array ($req_number[0]), which is likely an error. You'll want to correct those. Also: You should be using query parameters and prepared statements. Getting used to building SQL code from concatenating values like that is a SQL injection vulnerability waiting to happen.)
Instead of just referencing the first value in the array, loop over the array. Something like this:
for($i = 0; $i < count($req_number); $i++) {
// The code which uses $req_number, but
// referencing each value: $req_number[$i]
}

PHP: make sessions from database

I am trying to make some sessions from my database.
What I wan't to do is, take a specific row in my database an add the value of each column to a session.
The name of the session should then be the name of the column.
I am running ´session_start();´
Here is the code and my attempt to do it:
function opponent_data(){
try {
$PDO_new = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$PDO_new->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$opponent = $PDO_new->prepare("SELECT * FROM Info WHERE user_name =:username");
$opponent->bindParam(":username", $_SESSION["opponent"]);
$opponent->execute();
//my failed attempt
$row = $opponent->fetch(PDO::FETCH_ASSOC);
$column = $opponent->fetch(PDO::FETCH_COLUMN);
$col_count = $opponent->columnCount();
for ($x = 0; $x <= $col_count; $x++) {
$_SESSION[$column[$x]] = $row[$x];
}
}catch (PDOException $e) {
$error[] = $e->getMessage();
}
}
Thanks for any help.
Sorry for the bad tittle, I didn't knew what i should call this.
When you use PDO::FETCH_COLUMN a column number is expected ie.:
$stmt->fetch(PDO::FETCH_COLUMN, $number_of_column);
It would be easier to loop through the columns from your PDO::FETCH_ASSOC
$row = $opponent->fetch(PDO::FETCH_ASSOC);
foreach ($row as $columnName => $columnVal){
$_SESSION[$columnName] =$columnVal;
}
$x is a number... But you are fetching your result into an associative array. $row[$x] subsequently does not exist.
fetchColumn() and fetchAssoc() returns only 1 column... These should be in while-loops...

Two Dimensional arrays and both indexes

I have data coming from a query and loading it into a 2 dimensional array inside a loop.
I have the below code but when it prints out the array the index is missing.
How do I load a 2 dimensional aray with the first index being the $id value and second index being the $UserEmail and then how would I loop through the array to pull out each index ($id, $UserEmail)?
//the query
$query = "select id, UserEmail from User";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$ue = $row['UserEmail'];
$id = $row['id'];
if (strpos($ue,','))
{
$UserArrayEmail = explode(',',$ue);
foreach ($UserEmailArray as $u)
{
$ArrayTerm[$id][] = $u;
}
}
}
//looping through the array and getting value from $id and $UserEmail
foreach( $ArrayTerm as $ArrayT ) {
print_r($ArrayT);
foreach( $ArrayT as $value ) {
echo $value . "<br/>";
}
}
Please help.
mysql_connect() is deprecated your solution should use PDO instead.
This is how it could be done with PDO and will fix the indexes:
//fetch array from query
try {
$dbh = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
} catch (PDOException $e) {
// db error handling
}
$sth = $dbh->prepare("select id, UserEmail from user");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
while($row = $sth->fetch())) {
$emails = $row['UserEmail'];
$id = $row['id'];
if (strpos($emails,',')) {
$UserEmailArray = explode(',',$emails);
foreach ($UserEmailArray as $email) {
$ArrayT[$id][] = $email;
}
}
}
//repeat the same but with PDO data with other loops
}
Additionally, storing a list of data (in your case emails) in a single db column is not great for db normalization.
You have no type safety (VARCHAR can containanything), no referential integrity, no way of actually processing the data with the db (in SELECTs, JOINs etc).
For the db, the list of email addresses is just a bunch of random characters.
The relational database model has a simple rule: one attribute, one value. So if you have multiple values, you have multiple rows. That's what you should fix first. You'll need another table named "user_email_addresses" or something.
With this new table it could be something like:
function html_escape($raw) {
return htmlentities($raw, ENT_COMPAT , 'utf-8');
}
function log_exceptions($exception) {
echo $exception->getMessage(), '<br />', $exception->getTraceAsString();
}
set_exception_handler('log_exceptions');
$database = new PDO( 'mysql:host=localhost;dbname=DB', 'USER', 'PASS', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );
$user_emails = array();
$emails = $database->query('
SELECT user_id , email
FROM user_email_addresses');
foreach ($emails as $email)
$user_emails[ $email['user_id'] ][] = $email['email_address'];
//address list
foreach ($user_emails as $user_id => $email_addresses) {
echo 'User: ' . html_escape($user_id) . '<br />';
foreach ($email_addresses as $email_address)
echo html_escape($email_address) . '<br />';
echo '<br />';

How to get a list of databases?

I was wondering if there's a way in PHP to list all available databases by usage of mysqli. The following works smooth in MySQL (see php docs):
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
Can I Change:
$db_list = mysql_list_dbs($link); // mysql
Into something like:
$db_list = mysqli_list_dbs($link); // mysqli
If this is not working, would it be possible to convert a created mysqli connection into a regular mysql and continue fetching/querying on the new converted connection?
It doesn't appear as though there's a function available to do this, but you can execute a show databases; query and the rows returned will be the databases available.
EXAMPLE:
Replace this:
$db_list = mysql_list_dbs($link); //mysql
With this:
$db_list = mysqli_query($link, "SHOW DATABASES"); //mysqli
I realize this is an old thread but, searching the 'net still doesn't seem to help. Here's my solution;
$sql="SHOW DATABASES";
$link = mysqli_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql: ' . mysqli_error($link).'\r\n');
if (!($result=mysqli_query($link,$sql))) {
printf("Error: %s\n", mysqli_error($link));
}
while( $row = mysqli_fetch_row( $result ) ){
if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
echo $row[0]."\r\n";
}
}
Similar to Rick's answer, but this is the way to do it if you prefer to use mysqli in object-orientated fashion:
$mysqli = ... // This object is my equivalent of Rick's $link object.
$sql = "SHOW DATABASES";
$result = $mysqli->query($sql);
if ($result === false) {
throw new Exception("Could not execute query: " . $mysqli->error);
}
$db_names = array();
while($row = $result->fetch_array(MYSQLI_NUM)) { // for each row of the resultset
$db_names[] = $row[0]; // Add db name to $db_names array
}
echo "Database names: " . PHP_EOL . print_r($db_names, TRUE); // display array
Here is a complete and extended solution for the answer, there are some databases that you do not need to read because those databases are system databases and we do not want them to appear on our result set, these system databases differ by the setup you have in your SQL so this solution will help in any kind of situations.
first you have to make database connection in OOP
//error reporting Procedural way
//mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//error reporting OOP way
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL & MYSQLI_REPORT_STRICT;
$conn = new mysqli("localhost","root","kasun12345");
using Index array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_NUM)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row[0] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row[0];
}
}
same with Assoc array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row["Database"] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row["Database"];
}
}
same using object of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($obj = $result->fetch_object()){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if( $obj->Database == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'. $obj->Database;
}
}

Categories