PHP: Strange behaviour while calling custom php functions - php

I am facing a strange behavior while coding in PHP with Flex. Let me explain the situation:
I have two funcions lets say:
populateTable() //puts some data in a table made with flex
createXML() //creates an xml file which is used by Fusion Charts to create a chart
Now, if i call populateTable() alone, the table gets populated with data but if i call it with createXML(), the table doesn't get populated but createXML() does it's work i.e. creates an xml file.
Even if i run following code, only xml file gets generated but table remains empty whereas i called populateTable() before createXML(). Any idea what may be going wrong?
MXML Part
<mx:HTTPService id="userRequest" url="request.php" method="POST" resultFormat="e4x">
<mx:request xmlns="">
<getResult>send</getResult>
</mx:request>
and
<mx:DataGrid id="dgUserRequest" dataProvider="{userRequest.lastResult.user}" x="28.5" y="36" width="525" height="250" >
<mx:columns>
<mx:DataGridColumn headerText="No." dataField="no" />
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Age" dataField="age"/>
</mx:columns>
PHP Part
<?php
//--------------------------------------------------------------------------
function initialize($username,$password,$database)
//--------------------------------------------------------------------------
{
# Connect to the database
$link = mysql_connect("localhost", $username,$password);
if (!$link)
{
die('Could not connected to the database : ' . mysql_error());
}
# Select the database
$db_selected = mysql_select_db($database, $link);
if (!$db_selected)
{
die ('Could not select the DB : ' . mysql_error());
}
//
populateTable();
createXML();
# Close database connection
}
//--------------------------------------------------------------------------
populateTable()
//--------------------------------------------------------------------------
{
if($_POST['getResult'] == 'send')
{
$Result = mysql_query("SELECT * FROM session" );
$Return = "<Users>";
$no = 1;
while ( $row = mysql_fetch_object( $Result ) )
{
$Return .= "<user><no>".$no."</no><name>".$row->name."</name><age>".$row->age."</age><salary>". $row->salary."</salary></session>";
$no=$no+1;
$Return .= "</Users>";
mysql_free_result( $Result );
print ($Return);
}
//--------------------------------------------------------------------------
createXML()
//--------------------------------------------------------------------------
{
$users=array
(
"0"=>array("",0),
"1"=>array("Obama",0),
"2"=>array("Zardari",0),
"3"=>array("Imran Khan",0),
"4"=>array("Ahmadenijad",0)
);
$selectedUsers=array(1,4); //this means only obama and ahmadenijad are selected and the xml file will contain info related to them only
//Extracting salaries of selected users
$size=count($users);
for($i = 0; $i<$size; $i++)
{
//initialize temp which will calculate total throughput for each protocol separately
$salary = 0;
$result = mysql_query("SELECT salary FROM userInfo where name='$users[$selectedUsers[$i]][0]'");
$row = mysql_fetch_array($result))
$salary = $row['salary'];
}
$users[$selectedUsers[$i]][1]=$salary;
}
//creating XML string
$chartContent = "<chart caption=\"Users Vs Salaries\" formatNumberScale=\"0\" pieSliceDepth=\"30\" startingAngle=\"125\">";
for($i=0;$i<$size;$i++)
{
$chartContent .= "<set label=\"".$users[$selectedUsers[$i]][0]."\" value=\"".$users[$selectedUsers[$i]][1]."\"/>";
}
$chartContent .= "<styles>" .
"<definition>" .
"<style type=\"font\" name=\"CaptionFont\" size=\"16\" color=\"666666\"/>" .
"<style type=\"font\" name=\"SubCaptionFont\" bold=\"0\"/>" .
"</definition>" .
"<application>" .
"<apply toObject=\"caption\" styles=\"CaptionFont\"/>" .
"<apply toObject=\"SubCaption\" styles=\"SubCaptionFont\"/>" .
"</application>" .
"</styles>" .
"</chart>";
$file_handle = fopen('ChartData.xml','w');
fwrite($file_handle,$chartContent);
fclose($file_handle);
}
initialize("root","","hiddenpeak");
?>

If your createXML function generates xml on the same exact page generation, and it sends a Content-Type of application/xml then it might be possible the table stuff doesn't parse. Again, this would only be guessing until you provided code.

Well, the only answer is that createXML somewhere overwrites/deletes your (probably global) table. Please have a look into your code again.

like comments given above, will be difficult without more info/codes/backend db:
however my wild guest:
populateTable() insert data to db
createXML() query data inserted by populateTable().
looks like 2 diff db conn. certain db required u to do commit inside your code, if so, make sure you do it inside populateTable() before closing the db conn.

Related

SQL print/echo dumping php code into HTML

I am very, very new to HTML/PHP so I'm probably going to misuse terminology, bear with me please.
I'm trying to print the results of my SQL query in HTML in a <p> element using <br> to separate them. I know it's not the best way but it's an easy one and will help me practice this.
Anyway my problem is instead of printing the "movieName" attribute I'm trying to print it dumps some of the PHP code into the <p> element body instead.
I don't know what information to provide to make it easier on you to spot the problem so please request any relevant details.
Here's the php code (I've "censored" my info because you can easily access my student account with it):
<?php
if (array_key_exists('searchInput', $_GET)) {
$search = $_GET['searchInput'];
// Connecting, selecting database
$dbconn = pg_connect("host=**** port=15432 dbname=**** user=**** password=****")
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = "SELECT movieName
FROM DatabaseProject.Movie M
WHERE M.movieName LIKE $search";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$field = $row["movieName"];
print("$field<br>");
}
} else {
print("0 results");
};
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
}
?>
This is what I get printed into the webpage:
num_rows > 0) { // output data of each row
while($row = $result->fetch_assoc()) {
$field = $row["movieName"];
print("$field
");
}
} else {
print("0 results");
};
// Free resultset pg_free_result($result);
// Closing connection pg_close($dbconn);
}
?>

Calling a PHP function containing SQL query in separate PHP function building HTML table on separate page?

Basically, I'm trying to organize my code cleaner. I have a bunch of SQL queries which I am storing in a file called Queries.PHP. Example:
//Queries.php
//Connects to Database
$dbh=mysql_connect ("localhost", "~", "~") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("~") or ("Database not found");
function hi3() {
$query = "SELECT AVG(NULLIF(`~`, 0)) FROM `~` WHERE `~` BETWEEN '~' AND '~';";
$result = mysql_query($query) or die ( $result.mysql_error());
$row = mysql_fetch_array($result);
echo "~";
}
Then, on a separate page, I have code that is building HTML table headers and a separate function building the contents:
include Queries.php;
function BuildHTMLTableHeaders {
echo HTML table headers;
BuildHTMLTableBody();
echo </table>;
}
function BuildHTMLBody {
echo <tr>;
echo <td>;
hi3();
echo </td>;
echo </tr>;
...
}
Now, here's my problem: when I call hi3(), the rest of the table doesn't build. Why?
Your logic in BuildHTMLBody is flawed. You're only ever going to echo out 1 table row/cell because you're not looping through the results you get from your function.
function hi3() {
$query = "SELECT AVG(NULLIF(`~`, 0)) FROM `~` WHERE `~` BETWEEN '~' AND '~';";
$result = mysql_query($query) or die ( $result.mysql_error());
return $result;
}
function BuildHTMLBody {
$rows = hi3();
while($row = mysql_fetch_array($rows)) {
echo '<tr>';
echo '<td>' . $row['data'] . '</td>';
echo '</tr>';
}
}
Notice I return the results of hi3() and assign the results to a variable in BuildHTMLBody() and loop through them.
I haven't tested this, so I'm not sure if there are any syntax errors. Also, I would suggest using mysqli_. mysql_ is deprecated.

How to get one row of all column fields from a mySQL database in PHP?

How to get one specific row of all column fields from a mySQL database in PHP?
How would I do this, code wise? If you do respond, could you dumb it down for someone with very little experience?
Or could someone give me the code? Sorry if that is frowned upon,but I tried writing my own, but my lack of understanding and general incompetence foiled me. I even tried posting my code here, but it didn't help, and I like to get at least some work done on this project. I would repost my code again, but I dont want to duplicate posts.
You can use mysql_fetch_field to get column information from a result and return as an object.
<?php
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('database');
$result = mysql_query('select * from table');
if (!$result) {
die('Query failed: ' . mysql_error());
}
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
echo "Information for column $i:<br />\n";
$meta = mysql_fetch_field($result, $i);
if (!$meta) {
echo "No information available<br />\n";
}
echo "<pre>
blob: $meta->blob
max_length: $meta->max_length
multiple_key: $meta->multiple_key
name: $meta->name
not_null: $meta->not_null
numeric: $meta->numeric
primary_key: $meta->primary_key
table: $meta->table
type: $meta->type
unique_key: $meta->unique_key
unsigned: $meta->unsigned
zerofill: $meta->zerofill
</pre>";
$i++;
}
mysql_free_result($result);
?>
Read mone in:
http://php.net/manual/en/function.mysql-fetch-field.php
Or you can use:
$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['names'];
}
// now $storeArray will have all the names.
Read more in:
https://stackoverflow.com/a/5229533/3653989
http://php.net/manual/en/function.mysql-fetch-array.php

jquery autocomplete with php file that queries a mysql database

i'm trying to use a jquery autocomplete text-input with a mysql database for autocomplete suggestions. From a tutorial i got the following php function that is used to query a database.
<?php
include "db_connect.php";
$search = protect($_GET['term']);
$result = mysql_query("SELECT planeID FROM `planes` WHERE `planeID` LIKE '%$search%' ")
or die('Something went wrong');
$json = '[';
$first = true;
while ($row = mysql_fetch_assoc($result))
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['planeID'].'"}';
}
$json .= ']';
echo $json;
within the chrome networkpanel, i can see, that after each input into my textfield a request to "suggest_planeID.php?term=d-" i sent but i don't reveive any suggestion.
the database looks like this:
i have ha DatatBase called "test" with a table caled "planes" inside. This table has two columns 'planeID' and 'planeType".
is there any chance to debug the php file to find the error or does anyone here already see the error?

How to get or set the Database character encoding when using PHP ODBC Functions?

If I use odbc functions to connect to a database in PHP, How can I get or set the database character encoding? is there a function in PHP that I can use to do that?
An example of the odbc functions used in php script
<?php
//Connecting To The Database and getting $conn Variable
$conn = odbc_connect("database","username","password");
//Connection Check
if (!$conn)
{
echo "Database Connection Error: " . $conn;
}
$sqlResults = "SELECT EmpID AS EmployeeID, EmpName AS EmployeeName FROM Emp ORDER BY EmpName ASC";
$rsResults = odbc_exec($conn,$sqlResults);
if (!$rsResults)
{
echo "No Data Avialable";
}
else
{
while ( odbc_fetch_row($rsResults) )
{
$EmployeeID = odbc_result($rsResults,"EmployeeID");
$EmployeeName = odbc_result($rsResults,"EmployeeName");
//Printing the output
echo '<p>'. $EmpolyeeID . ' , ' . $EmployeeName . '</p>';
}
}
//Closing The Database
odbc_close($conn);
?>
You can find information on this here at Rob Allens dev notes page
rob allens dev notes

Categories