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);
}
?>
Related
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.
I've tried like twenty times and the closest I got was when I put in a variable stored in row 1 of the db and it returned the content the last row in the db. Any clarity would be extremely helpful. Thanks.
// Create connection
$coco = mysqli_connect($server, $user, $pass, $db);
// Check connection
if (!$coco) { die("Connection failed: " . mysqli_connect_error()); }
// Start SQL Query
$grabit = "SELECT title, number FROM the_one WHERE title = 'on' AND (number = 'two' OR number='0')";
$result = mysqli_query($coco, $grabit);
// What I need it to do
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$titleit = $row["title"];
$placeit = $row["number"];
$incoming = 'Help';
if ($titleit[$_REQUEST[$incoming]]){
$message = strip_tags(substr($placeit,0,140));
}
echo $message;
}
} else {
echo "not found";
}
mysqli_close($coco);
Put the input that you want to match into the WHERE clause of the query, rather than selecting everything and then testing it in PHP.
$incoming = mysqli_real_escape_string($coco, $_POST['Help']));
$grabit = "SELECT number FROM the_one WHERE title = '$incoming' AND number IN ('two', '0')";
$result = mysqli_query($coco, $grabit);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['number'];
}
} else {
echo "not found";
}
I think you need to add a break; in that if or I would assume it would go through each row in the database and set message if it matches the conditional. Unless you want the last entry that matches...if not you should debug:
if ($titleit[$_REQUEST[$incoming]]){
// set message
}
and see when it's getting set. That may not be the issue, but it's at least a performance thing and could explain getting the last entry
Have you tried print_r($row) to see the row or adding echos to the if/else to see what path it's taking?
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
I have successfully saved a number of SQL UPDATE statements to MySQL and now I want to retrieve them and have PHP process them. The code is below.
When I echo $query I get the correct SQL statements from the DB, but then when I try to process them, I get an error Warning: mysqli_query() [function.mysqli-query]: Empty query
It makes no sense to me and is driving me nuts! Do I have to do something else to $query so PHP can process it?
$num_rows = mysqli_num_rows($resultSQL);
if ($num_rows > 0)
{
while ($row = mysqli_fetch_array($resultSQL))
{
$strSQLupd[] = $row['uSQL'];
}
foreach ($strSQLupd as $query) {
$resultSQLupd = mysqli_query($link,
$query
);
if (!$resultSQLupd)
{
$error = 'Error fetching data: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
}
}
Are you setting the value of $link somewhere and is it required for what you're doing in this application? Also, remember that var_dump($varname); is always a helpful debugging tool.
foreach ($strSQLupd as $query) {
// put a var_dump below
var_dump($query);
$resultSQLupd = mysqli_query($query
);
if (!$resultSQLupd)
{
$error = 'Error fetching data: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
}
Give this a shot and look at the query string dumped to the screen. It may be null which is what's producing your error.
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.