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();
}
}
}
Related
$projects = array('1' => $link1, '2' => $link2);
function server_status($projects) {
foreach ($projects as $server) {
$api_status = ping_api($server);
if ($api_status == 1) {
$json = json_decode(file_get_contents($server), true);
foreach ($json as $obj) {
if ($obj['online'] < 1) {
// OFFLINE
return -1;
}
else {
// ONLINE
return $obj['online'];
}
}
} else {
// MAINTENANCE
return 0;
}
}
}
function cache_status($data) {
echo $data;
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=test", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
foreach ($data as $status) {
// server id + status
$sql = "UPDATE projects SET status=:status WHERE id=:server_id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':status', $status, PDO::PARAM_INT);
$stmt->bindParam(':server_id', 1, PDO::PARAM_INT);
$stmt->execute();
}
}
$problem = array(server_status($projects));
print_r($problem);
My problem is, when I print_r the variable $problem it should return two results in array, since there are two results but it only returning the first result from array as an .. example: Array ( [0] => 260 )
IF anyone is kind enough to look at my code and tell me what I am doing wrong, I would be very greatful
You are using return statement inside your loop that is why it breaks your loop on first iteration and returns what ever you have mentioned to the original call of function. To resolve this issue you need to collect the response from each iteration in array and in the end of function return your response for each iteration something like
function server_status($projects) {
$response= array();
$status = 0; // default status
foreach ($projects as $server) {
$api_status = ping_api($server);
if ($api_status == 1) {
$json = json_decode(file_get_contents($server), true);
foreach ($json as $obj) {
if ($obj['online'] < 1) {
// OFFLINE
$status= -1;
}
else {
// ONLINE
$status = $obj['online'];
}
}
}
$response[] = array('server'=>$server,'status'=>$status);
}
return $response;
}
I have a database at local server. I am trying to access this database. I have table of venueTypeMaster in the database. I tried to get all the venuetypes from database. But when I run the script message I get is - 'No database selected'.
I have a class in which I have created two functions in php script. For createVenue it dose not send any message and the query has been executed successfully. But for getVeunueTypes it is showing this message. Connection for both is same.
DB Script:
<?php
include_once("config.php");
include_once("exceptions.php");
class DB {
static $con;
public static function getConnection() {
try {
if ( DB::$con == null ) {
DB::$con = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
if ( DB::$con) {
$status = mysqli_select_db(DB::$con,DB_NAME);
if (! $status ) throw new DBSelectionExcpetion(mysqli_error());
return DB::$con;
} else {
$e = new DBConnectionException(mysqli_error());
throw $e;
}
}
return DB::$con;
} catch(DBConnectionException $e) {
throw $e;
} catch(DBSelectionExcpetion $de) {
throw $de;
}
return null;
}
?>
venueTypes script
<?php
include("exceptions.php");
include("DB.php");
include("config.php");
class VenueTypes {
public function getVenueTypes() {
try {
$con = DB::getConnection();
$query = "select * from venueTypeMaster";
$rs = mysql_query($query) or die (json_encode(array("result"=>-1, "message"=>mysql_error())));
$n = mysql_num_rows($rs);
$vt = array();
if ( $n > 0 ) {
while ( $row = mysql_fetch_assoc($rs)) {
$vt[] = $row;
}
$result = array("result"=>1, "message"=>"success", "venueTypes" => $vt);
return json_encode($result);
} else {
$result = array("result"=>-1, "message"=>"Venue types list is empty");
return json_encode($result);
}
} catch(DBConnectionException $e) {
$result = array("result"=>-1, "message"=> $e -> getMessage());
return json_encode($result);
}
return null;
}
public function createVenueType($fields) {
try {
$required = array("venuetype", "active", "entry_by", "entry_date", "entry_time", "last_modify_date", "ip_addr","venue_name");
$actual = array_keys($fields);
$intersection = array_intersect($required, $actual);
$n1 = sizeof($required);
$n2 = sizeof($intersection);
if ( $n1 != $n2 ) {
throw new MissingParameterException();
}
$con = DB::getConnection();
$keys = array_keys($fields);
$values = array_values($fields);
$columns = implode(",", $keys);
$n = sizeof($values);
for($i=0;$i<$n; $i++) {
$values[$i] = "'" . mysqli_real_escape_string($con,$values[$i]) . "'";
}
$columnValues = implode(",", $values);
$query = "insert into venuetypemaster($columns) values($columnValues)";
mysqli_query($con,$query) or die (json_encode(array("result"=>-1, "message"=>mysqli_error())));
$af = mysqli_affected_rows($con);
if ( $af == 1 ) {
$venuetypeId = mysqli_insert_id($con);
$result = array("result"=>1, "message"=>"success", "venuetypeId" => $venuetypeId);
return json_encode($result);
} else {
$result = array("result"=>-1, "message"=>"Failed to register");
return json_encode($result);
}
} catch(DBConnectionException $e) {
$result = array("result"=>-1, "message"=> $e -> getMessage());
return json_encode($result);
}
return null;
}
?>
getVenueType script
<?php
header("Content-type: application/json");
if ( $_SERVER['REQUEST_METHOD']=='GET') {
include_once ("../include/VenueTypes.php");
try {
$v = new VenueTypes();
$response = $v -> getVenueTypes();
//$response is null means something went wrong as a result we got null result from above statement
if ( $response == null ) {
$response = json_encode(array("result" => -2, "message" => "Empty result"));
echo $response;
} else {
echo $response;
}
} catch(Exception $e) {
$result = array("result" => -1, "message" => $e -> getMessage());
echo json_encode($result);
}
} else {
$result = array("result" => -3, "message" => "Unsupported method : " . $_SERVER['REQUEST_METHOD']);
echo json_encode($result);
}
?>
Can anyone help please.. Thank you..
The problem is that you are mixing between the mysqli_xxx() and mysql_xxx() functions. These two libraries are not compatible with each other; you must only use one or the other throughout your code.
Since the mysql_xxx() functions are obsolete and deprecated, that means you should only use mysqli_xxx().
Change all occurrences of mysql_ in your code to mysqli_.
You will also need to make other changes to these lines of code -- notably this will include adding the DB reference variable (ie the variable returned by getConnection()), but some other syntax changes may also be necessary.
Hi guys I have a problem with getting a variable outside and after an if statement. Little code explanation: $gameid or $id is sent via ajax to this file. Now $id have always a value and if (isset($_GET['id'])) { is true. The insert and select querys work very well. The problem is that I cant get the variable $answer or $question[0]['question']; after the second if statement. I can get them when I change the second if (isset($_GET['id'])) { to else { but then anyhow there become two rows in my database inserted, the first is right and the second one is empty. Now why cant I get the variables $answer and $question[0]['question']; after the second if condition?
The error log shows: Notice undefined variable question.
<?php
$hostname='localhost';
$user='';
$password='';
if (isset($_GET['gameid'])) {
$gameid = $_GET['gameid'];
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
echo $id;
}
if (isset($_GET['questionid'])) {
$questionid = $_GET['questionid'];
}
$new = 0;
if (isset($_GET['gameid'])) {
try {
$dbh = new PDO("mysql:host=$hostname;dbname=max_com_db_socame",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT *
FROM questions_de
WHERE id = '$questionid'
LIMIT 1";
if ($res = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$question = $res->fetchAll();
}
if($question > 0) {
//do something
} else {
echo "Sorry something happen wrong with our servers.";
}
}
catch(PDOException $e) {
}
if ($question[0]["answerm²"] == 0 && $question[0]["answerm³"] == 0) {
$answer = "answer_m";
} else {
$answer = "answerm³";
}
}
if (isset($_GET['id'])) {
try {
$dbh = new PDO("mysql:host=$hostname;dbname=max_com_db_socame",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT username
FROM user
WHERE id = '$id'
LIMIT 1";
if ($res = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$user2name = $res->fetchAll();
}
if($user2name > 0) {
//do something
} else {
echo "Sorry something happen wrong with our servers.";
}
}
catch(PDOException $e) {
}
try {
$dbh = new PDO("mysql:host=$hostname;dbname=max_com_db_socame",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT *
FROM questions_de
LIMIT 1"; //
if ($res = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$question = $res->fetchAll();
}
if($question > 0) {
//do something
} else {
echo "Sorry something happen wrong with our servers.";
}
}
catch(PDOException $e) {
}
if ($question[0]["answerm²"] == 0 && $question[0]["answerm³"] == 0) {
try {
$dbh = new PDO("mysql:host=$hostname;dbname=max_com_db_socame",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO game_create (user1, user2, user1name, user2name, question, questionid, answer)
VALUES ('".$_COOKIE["userid"]."', '".$id."', '".$_COOKIE["username"]."', '".$user2name[0]["username"]."', '".$question[0]['question']."', '".$question[0]['id']."', '".$question[0]['answer_m']."')";
if ($dbh->query($sql)) {
//echo "New Record Inserted Successfully";
} else{
// echo "Data not successfully Inserted.";
}
$new = $dbh->lastInsertId();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if ($new > 0) {
} else {
echo 'Sorry something went wrong.';
}
$answer = "answer_m";
}
else {
try {
$dbh = new PDO("mysql:host=$hostname;dbname=max_com_db_socame",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO game_create (user1, user2, user1name, user2name, question, questionid, answer)
VALUES ('".$_COOKIE["userid"]."', '".$id."', '".$_COOKIE["username"]."', '".$user2name[0]["username"]."', '".$question[0]['question']."', '".$question[0]['id']."', '".$question[0]['answer_m³']."')";
if ($dbh->query($sql)) {
//echo "New Record Inserted Successfully";
} else{
// echo "Data not successfully Inserted.";
}
$new = $dbh->lastInsertId();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if ($new > 0) {
} else {
echo 'Sorry something went wrong.';
}
$answer = "answerm³";
}
}
?>
On the line:
if (isset($_GET['gameid'])) {..}
You're checking if the $_GET['gameid'] is set, with other words, if it has a value. As you stated, $_GET['gameid'] only has a value when $_GET_[id] doesn't have value. As you said, $_GET_['id] always has value, so $_GET['gameid'] wont be initialized.
Therefor, it won't get past this condition, and won't reach the line of $question = $res->fetchAll();, which initializes the variable.
The same thing stands for $answer, since it's in the same if statement and is also doing conditional checking on the $question variable.
To solve this problem, either initialize the $_GET['gameid'] variable by sending it to the PHP script without any conditions or remove the if (isset($_GET['gameid'])) {..} statement.
MY code is:
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("select userid,fname,type from native_users where email=:email and pass=:pass");
$stmt->bindParam(':email', $username);
$stmt->bindParam(':pass', $password);
$stmt->execute();
if($stmt->rowCount() > 0)
{
$_SESSION['uid']=$stmt->fetchColumn(0); //working
$_SESSION['fname']=$stmt->fetchColumn(1); //not working
$utype=$stmt->fetchColumn(3); // not working
if($utype == "admin")
{
// send to admin page
}
else
{
//send to user page
}
}
else
{
echo"Incorrect data.";
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
I am new to PHP, I basically do Java.
I read here that:
There is no way to return another column from the same row if you use
PDOStatement::fetchColumn() to retrieve data.
In java, there is ResultSet#getString() funtion to do this.
What is the PHP equivalent of this?
You can use:
$result = $sth->fetch();
$result[0] will give userid
$result[1] will give fname
$result[2] will give type
Please read this
fetchColumn(), Returns a single column from the next row of a result
set.
Please read this for detail.
Use PDO::fetchAll() :
$rows = $stmt->fetchAll();
foreach ($rows as $v) {
echo $v['userid'] . " " . $v['fname'] . " " . $v['type'] ;
}
}
or just print_r($rows) you will notice that it's an associative array.
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