Two Dimensional arrays and both indexes - php

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

Related

php, how to connect to a database as a class, send sql statments and return the result

Forgive me if the question is a little odd
I can clarify if needed:
I have the code that can connect to a mysql database as normal, however i have encapsulated it as a class:
<?php
define("HOST", "127.0.0.1"); // The host you want to connect to.
define("USER", "phpuser"); // The database username.
define("PASSWORD", "Secretpassword"); // The database password.
class DBConnection{
function conn($sql, $database){
$DB = new mysqli(HOST,USER,PASSWORD,$database);
if ($DB->connect_error){
die("Connection failed: " . $DB->connect_error);
exit();
}
if ($result = $DB->query($sql)){
return TRUE;
$DB->close();
}
else{
echo "Error: " . $sql . "<br>" . $DB->error;
$DB->close();
}
}
}
?>
I have done it this way so i can include this class in any subsequent php page and allow them to send it an sql statment and the database, see below as an example:
$sql = ("INSERT INTO users (first_name, last_name, username, email, password, group_level) VALUES ('John', 'Doah','JDoah', 'example#email', 'password', 'user')");
$DB = new DBConnection;
$result = $DB->conn($sql,"members");
if ($result ==TRUE){
return "Record added sucessfully";
}
This works fine.
however, im looking to send other sql statments to DBConnection.
How do i do that and to have it pass back any results that it recives? errors, boolean, row data etc. The caller will worry about parsing it.
Hopefully that makes sense.
This is an old class I used to use way back in the days of mysql still works but will need to be updated for mysqli or newer
class DBManager{
private $credentials = array(
"host" => "localhost",
"user" => "",
"pass" => "",
"db" => ""
);
function DBManager(){
$this->ConnectToDBServer();
}
function ConnectToDBServer(){
mysql_connect($this->credentials["host"],$this->credentials["user"],$this->credentials["pass"]) or die(mysql_error());
$this->ConnectToDB();
session_start();
}
function ConnectToDB(){
mysql_select_db($this->credentials["db"]) or die(mysql_error());
}
function Insert($tableName,$data){
$parameters = '';
$len = count($data);
$i = 0;
foreach($data as $key => $value){
if(++$i === $len){
$parameters .= $key . "='$value'";
}else{
$parameters .= $key . "='$value'" . ", ";
}
}
$query = "INSERT INTO $tableName SET $parameters";
mysql_query($query) or die(mysql_error());
return true;
}
function GetRow($tableName,$select,$where){
$selection = '';
$len = count($select);
$i = 0;
foreach($select as $key){
if(++$i === $len){
$selection .= $key;
}else{
$selection .= $key . ",";
}
}
$whereAt = '';
foreach($where as $key => $value){
$whereAt .= $key . "='$value'";
}
$query = "SELECT $selection FROM $tableName WHERE $whereAt";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
return $row;
}
}
}
The key things here is you can create a persistent connection to your database without rewriting a bunch of code
Example
global $DB;
$DB = new DBManager();
Since the connection happens in the constructor you will now have a connection on the page you call this code and can begin getting and setting to the database through use of $DB->GetRow() and $DB->Insert() which makes things much easier and was modeled after the $wpdb instance which is a class that manages the database in wordpress sites
Examples
For these examples we will assume you have a table as such
Insert new student
//create an associative array
$data = array(
"student_id" => 1,
"birth_date" => "02/06/1992",
"grade_level" => 4
);
//Send Call
$dm->Insert("student",$data);
Get data
//Create selection
$selection = array("grade_level");
//Create associative array for where we want to find the data at
$where = array(
"id" => 1
);
//Get Result
$result = $dm->GetRow("student",$selection,$where);
//do something with result
echo $result->grade_level;

MYSQL PHP PDO Fill table with database data

I want to give out a for every line in my database.
It seems that it is working but only returns the first column.
Note: There are values for the empty fields in database!
$columns = "Ticket, Last_Modified_Date, Requester";
Heres my code:
function getTicket($columns){
echo($columns);
global $db_host, $db_name, $db_user, $db_pass;
$db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$result = $db->prepare("SELECT $columns FROM tickets");
if ($result->execute()){
echo("<b>Successfully!</b><br><br>");
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
$col_names = explode(',', $columns);
foreach($rows as $row){
echo("<tr>");
foreach($col_names as $col_name){
if (!isset($row[$col_name])){
continue;
}
echo("<td>".$row[$col_name]."</td>");
}
echo("</tr>");
}
}
else{
echo("<b>FAILED!</b><br><br>");
}
$db = null;
}
->fetch() returns only one value of the rows.
Use ->fetchAll() ( PHP Documentation ) if you want to return all of your results.
There are a couple of issues here, first you should use ->fetchall() which will return ALL the result rows in one hit into an array.
Second you are overwriting your $result statement handle with the row being returned by ->fetch
function getTicket($columns){
global $db_host, $db_name, $db_user, $db_pass;
$db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$result = $db->prepare("SELECT $columns FROM tickets");
if ($result->execute()){
echo("<b>Successfully!</b><br><br>");
// CHANGES HERE
$rows = $result->fetchall(PDO::FETCH_ASSOC);
$col_names = explode(',', $columns); //make array of csv
foreach($rows as $row){
foreach( $col_names as $col_name ) {
echo '<td>' . $row[$col_name] . '</td>';
}
}
}else{
echo("<b>FAILED!</b><br><br>");
}
$db = null;
}

Import JSON in MySQL DB from Import.io

I'm trying to import data from a JSON feed using PHP into a MySQL database.
I have the code below but am not getting anywhere with it.
I keep just getting Connected to Database but nothing is being pulled in from the JSON data.
The JSON data is being created from a feed using import.io.
Any help appreciated
JSON data here
<?php
$data = file_get_contents('https://query.import.io/store/connector/e18543ae-48d1-47d3-9dc7-c3d55cab2951/_query?_user=363ec2db-fb95-413f-9a20-3fe89acbf061&_apikey=HOXvwSMX4HlmqH123i5HeELV6BwKq%2BFRInTzXc4nfl5VtP0pJyChxMT9AEiu1Ozi0vWZmUB%2BKcSsxHz2ElHNAg%3D%3D&format=JSON&input/webpage/url=http%3A%2F%2Fsports.yahoo.com%2Fgolf%2Fpga%2Fleaderboard');
$array = json_decode($data, true);
$rows = array();
$index = 0;
foreach($array['results'] as $mydata)
{
print_r($mydata);
echo "<br>";
foreach($mydata as $key => $value)
{
print_r ($key);
print_r ($value);
echo $index;
echo "<br><br>";
$rows[] = "('" . $value . "')";
}
echo "<br>";
$index++;
}
echo "<br><br><br>";
print_r ($rows);
$values = implode(",", $rows);
echo "<br><br><br>";
print_r ($values);
$hostname = 'localhost'; // write the rest of your query
$username = 'username';
$password = 'password';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
echo 'Connected to database<br />'; // echo a message saying we have connected
$count = $dbh->exec("INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($values)");
echo $count;// echo the number of affected rows
$dbh = null;// close the database connection
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
First of here we have to fetch every row and then do another loop to fetch every value contained in that row, in this way we will obtain a 2D Array containing the data to format to put after in the db.
$i = 0;
foreach($array['results'] as $result){
foreach ($result as $key => $value)
$rows[$i][] = "'" . $value . "'";
$i++;
}
Then, here we format the data in order to fit our query that will be executed for every row fetched before.
try{
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
foreach ($rows as $row) {
$row = implode(",",$row); //making a string from an array with each item separated by comma
$query = "INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($row)<br>";
$count = $dbh->exec($query);
}
$dbh = null;// close the database connection
}catch(PDOException $e){
echo $e->getMessage();
}

Compare multiple values in two arrays 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

Store variables from MySQL select to PHP class variables more efficiently when the table field names are identical to the class variable names?

I am selecting data from a database. The database field names are exactly the same as the class variable names. Is there a way to store this data into the class variables without specifying each one individually?
//gets info about a specified file.
//chosen based on a supplied $fileId
function getFileInfo($fileId)
{
//select info from database
$sql = "SELECT id, companyId, url, name, contentType, fileSize, saved, retrieved
FROM files
WHERE id = $fileId";
$results = $this->mysqli->query($sql);
$results = $results->fetch_object();
//store info into class variables
$this->id = $results->id;
$this->companyId = $results->companyId;
$this->url = $results->url;
$this->name = $results->name;
$this->contentType = $results->contentType;
$this->fileSize = $results->fileSize;
$this->saved = $results->saved;
$this->retrieved = $results->retrieved;
}
A quick and dirty way would ba a loop:
foreach($result as $var => $value) {
$this->$var = $value;
}
I'd propose this approach:
$nameMap = array(
'id',
'companyId',
'url',
'name',
'contentType',
'fileSize',
'saved',
'retrieved',
);
foreach( $nameMap as $attributeName ) {
$this->$attributeName = $results->$attributeName ;
}
While one could write
foreach($result as $var => $value) {
...
}
the outcome fully depends on backing table's structure. If you add further attributes to the table, your code might break.
Using $nameMap, the application still works.
Just use foreach structure:
foreach ($result as $column => $value) {
$this->$column = $value;
}
Not nice but will work.
Humm. Well, PDO has native functions for that, if you're not married to mysqli for some reason:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->NAME;
The biggest disadvantage I've found is that PDO doesn't support SSL connections between the PHP machine and the MySQL machine.

Categories