its me again with yet another query.If this is going to be too complexed then i wont even bother...so heres the query.
I have the title,artist,name of the person & dedication message stored in mysql.May be this is stupid..is it possible to create xml file to retrieve the above four information from the database. I have coded the below on the xml file but not sure whats missing.The config.php has database connection information.
Many thanks for your help!!!!
Nev
<?php
require("config.php");
$i=0;
$db = "SELECT * FROM songlist WHERE songtype='S' ORDER BY date_added DESC LIMIT 50";
$db = "SELECT songlist.artist, songlist.title, requestlist.name, requestlist.msg FROM songlist, requestlist WHERE requestlist.name <> '' and requestlist.songID = songlist.ID ORDER BY requestlist.t_stamp DESC LIMIT 20";
$count = 1;
while($results = $db->row())
{
$count++;
if(($count % 2)== 0)
?>
<?php echo('<?xml version="1.0" encoding="utf-8"?>'); ?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
<trackList>
<track>
<Song><?php echo $results['title']?></Song>
<album><![CDATA[<?php echo $results['artist']; ?>]]></album>
</track>
</trackList>
</playlist>
<?
$i++;
}
?>
You haven't explained what your problem is? Also, I would need information on the format required for the xml, or what commands you'd need to send to your database code.
It looks like you have some formatting errors as well. I can only guess at what would work, but try this:
1) At the beginning of the file, you seem to have forgotten the start tag
2) $i seems to be unused, delete it (?)
3) Your SQL statement is not only unenclosed in quotes, but would need to be sent to the database code (a complete guess since I don't know what's inside your config.php would be $db->query("your sql here");
4) delete: '); ?>
5) ... actually this is getting silly, I should probably just rewrite it for you!!!
The thing is, before anything else, I'd need to know If you NEED to use the config.php? Or if I could code using native php functions.
But this is still fraught with problems (since I don't know what requirements the formatting for the xml are for one) but I'll give it a go! So just tell me if you need to use your config.php or not, then if no, I'll quickly code something. Otherwise you're going to have to post the contents of config.php
Cheers
Ok here's my best guess at what would work:
<?xml version="1.0" encoding="utf-8"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
<trackList>
<?php
$DB_SERVER = "localhost";
$DB_NAME = "yourdatabasename";
$DB_USER = "yourdbuser";
$DB_PASSWORD = "yourpw";
mysql_connect($DB_SERVER, $DB_USER, $DB_PASSWORD);
mysql_select_db($DB_NAME);
$sql = "select * from songlist order by date_added desc limit 10";
$res = mysql_query($sql);
while ($result = mysql_fetch_assoc($res)){
?>
<track>
<Song><![CDATA[<?= $result['title']?]]></Song>
<album><![CDATA[<?= $result['artist']?>]]></album>
</track>
<?
}
?>
</trackList>
</playlist>
Just change your database name, user and password, then you will have your xml. However, you might want to change your album line above to:
Okay, your primary problem seems this:
$db = "SELECT * ..";
$db = "SELECT song ...";
while($results = $db->row())
{
You are assigning a string there, and immediately afterwards try to use it as some sort of database interface. Since I have no idea what is going on in your config script, or what weird database interface you use, it's easier explained with using the outdated mysql_functions:
$result = mysql_query("SELECT songlist.artist, ... goes here");
while($results = mysql_fetch_assoc($result))
{
The mysql_query runs your SELECT statement, and only then can you iterate over the results with mysql_fetch_assoc using the $result value that you got from mysql_query.
Note that you have to decide which of your two queries to actually run here. You cannot use two SELECT queries concurrently. (Or not not in your case at least.)
Related
I am trying to generate some xml with this php code here... I am trying to use this script for an ios app I am learning from as I go just to figure out how each of the parts fit i.e. (app, php, mysql, xml)
Here is my php script that my ios app is exicuting
<?php
header("Content-type: text/xml");
$username="*****";
$password="***";
$database=" *****";
$testcode=$_REQUEST['usercode']; ////testcode coming from ios app
//connect to database
$connect = mysql_connect('localhost',$username,$password) or die('No DB Connection');
//select database
$db = mysql_select_db('N_codes', $connect) or die("<b>Unable to select specified database</b>");
//Do some stuff here
$query = "SELECT codes FROM codes where id = '$testcode'"; //testcode coming from ios app
$result = mysql_query($query,$connect);
//XML STUFF
$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<entries>\n";
$row = mysql_fetch_assoc($result);
$xml_output .= "\t\t<code>" . $row['codes'] . "</code>\n";
$xml_output .= "</entries>";
echo $xml_output;
?>
This is all that it is producing
<?xml version="1.0"?>
<entries>
<code></code>
</entries>
What I am looking for is a code that should be between that is in the mysql database and is found by the user supplying a code that is passed to the php script.
Can anyone see whats missing?
I see a few "potential" problems with the code you provided above.
1. Is your table named codes and the field you're looking for also codes? Your SQL question is looking for a field name codes in a table called codes. It's hard to tell whether or not that's a problem but must rows represent a single field so the plural version of the word "code" makes me believe you made a mistake there.
$query = "SELECT code FROM codes where id = '$testcode'";
2. Try adding a die after the query that outputs [mysql_error][2] just in case an error occurred.
$result = mysql_query($query, $connect) or die(mysql_error($connect));
3. You should use mysql_real_escape_string when you use user supplied data in a SQL query.
$testcode = mysql_real_escape_string($_REQUEST['usercode'], $connect);
What is causing my php code to freeze? I know it's cause of the while loop, but I have $max_threads--; at the end so it shouldn't do that.
<html>
<head>
<?php
$db = mysql_connect("host","name","pass") or die("Can't connect to host");
mysql_select_db("dbname",$db) or die("Can't connect to DB");
$sql_result = mysql_query("SELECT MAX(Thread) FROM test_posts", $db);
$rs = mysql_fetch_row($sql_result);
$max_threads = $rs[0];
$board = $_GET['board'];
?>
</head>
<body>
<?php
While($max_threads >= 0)
{
$sql_result = mysql_query("SELECT MIN(ID) FROM test_posts WHERE Thread=".$max_threads."", $db);
$rs = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT post FROM test_posts WHERE ID=".$rs[0]."", $db);
$post = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT name FROM test_posts WHERE ID=".$rs[0]."", $db);
$name = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT trip FROM test_posts WHERE ID=".$rs[0]."", $db);
$trip = mysql_fetch_row($sql_result);
if(!empty($post))
echo'<div class="postbox"><h4>'.$name[0].'['.$trip[0].']</h4><hr />' . $post[0] . '<br /><hr />[Reply]</div>';
$max_threads--;
}
?>
</body>
</html>
First, I'd suggest completely getting rid of the extraneous HTML bits. Then, build up your code slowly, line-by-line to see if you can find the offending line. So write a script that just connects to the database and see what happens.
If you find for example that this code...
<?php
$db = mysql_connect("host","name","pass") or die("Can't connect to host");
mysql_select_db("dbname",$db) or die("Can't connect to DB");
?>
...is causing the freeze on its own, then it could easily be a problem with the MySQL server.
However, if the browser itself is crashing, that sounds like an issue with your system rather than something that PHP or MySQL is doing...
Try this 1 SQL query instead of those 1 + (4 * n) queries:
SELECT MIN(ID), post, name, trip FROM test_posts GROUP BY Thread
Maybe a LIMIT 50 (or whatever max # of threads to return) at the end as well, that could be a lot of data.
You can just loop over the results of this query instead of $max_threads and all the extra db calls, via while ($row = mysql_fetch_row($sql_result)) { /* echo(...); */ }.
Not sure that's exactly the same as what you're trying to fetch without knowing more about the data (getting the root post of each thread in a forum?), but it should be pretty close.
(P.S.: if that's a threaded 2ch-style forum deal, I'm not sure that's an ideal db design. A parent-child adjacency list might be better than maintaining a number count for each thread. Just a guess though.)
I'm thinking it's because you're hitting the sql database 4 times per loop. Is there any way you can maybe access it all at once, and then parse the incoming data from there?
$dbsql = 'SELECT * FROM my_database';
$result = mysql_query($dbsql);
while($row = mysql_fetch_array($result)) {
// Parse information here, rather than
// accessing the database for individual variables...
}
Something like that.
Update:
Other than what I've already said (and you've dismissed) all I see are some here & there coding quirks:
This part didn't have a space between echo and the string. The 'hr' element didn't have a starting bracket.
echo '<div class="postbox"><h4>'.$name[0].'['.$trip[0].']</h4><hr>' . $post[0] . '<br /><hr />[Reply]</div>';
'while' Shouldn't be capitalized.
while($max_threads >= 0)
Again, clean code is a good place to start, but that's all I've got, personally. I just recently cleaned up my own site, which was crashing IE (and no other browser), simply because it had too many markup errors. Hope it helps.
Maybe you can scatter calls to this simple function in yer code:
function of($required)
{
$args = func_get_args();
var_dump($args);
ob_flush();
flush();
}
of(__LINE__, $max_threads);
You can also use something like this for your queries:
function mydb_query($query, $db = null)
{
$args = func_get_args();
$result = call_user_func_array('mysql_query', $args);
if (!$result) {
of(array(__FUNCTION__), mysql_error(), $sql);
//return something else?
}
return $result;
}
$result = mydb_query("SELECT post, name, trip FROM test_posts WHERE ID = (SELECT MIN(ID) FROM test_posts WHERE Thread={$max_threads})", $db);
You should use mysqli/PDO/framework with support for prepared statements.
Probably the script is exceeding the maximum server execution time threshold, try this on the top of your file to confirm this:
ini_set('max_execution_time', '180');
I created the following script to query a table and return the first 30 results. The query returns 30 results, but they do not have any text or information. Why would this be?
The table stores Vietnamese characters. The database is mysql4.
Here's the page: http://saomaidanang.com/recentposts.php
Here's the code:
<?php
header( 'Content-Type: text/html; charset=utf-8' );
//CONNECTION INFO
$dbms = 'mysql';
$dbhost = 'xxxxx';
$dbname = 'xxxxxxx';
$dbuser = 'xxxxxxx';
$dbpasswd = 'xxxxxxxxxxxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpasswd ) or die('Error connecting to mysql');
mysql_select_db($dbname , $conn);
//QUERY
$result = mysql_query("SET NAMES utf8");
$cmd = 'SELECT * FROM `phpbb_posts_text` ORDER BY `phpbb_posts_text`.`post_subject` DESC LIMIT 0, 30 ';
$result = mysql_query($cmd);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html dir="ltr">
<head>
<title>recent posts</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p>
<?php
//DISPLAY
while ($myrow = mysql_fetch_row($result))
{
echo 'post subject:';
echo(utf8_encode($myrow ['post_subject']));
echo 'post text:';
echo(utf8_encode($myrow ['post_text']));
}
?>
</p>
</body>
Try using mysql_fetch_assoc() instead of mysql_fetch_row()
The former returns an array with each
result column stored in an array
offset, starting at offset 0.
The later returns an associative
array of strings where the column as
used as keys.
And in your program you are using the result as an associative array:
$myrow ['post_subject']
or you could try mysql_fetch_object() and access the data as $myrow->post_subject. If you feel the data is still not displayed, then do a print_r($myrow) to the the output. This way you will know for sure if the data has been returned.
If you use mysql_fetch_row(), you're going to need to access your data through numbered keys (ie $row[0], $row[1], etc). mysql_fetch_object() is the norm today in most applications to fetching rows as mentioned by Shamly.
I'm not a big fan of using PHP's provided functions to do daily coding. Instead, considering writing (or downloading) a class or a few functions to help do the job for you, like:
function my_query($query){
$return = array(); // stuff to return
$result = mysql_query($query);
while($row = mysql_fetch_object($result)){
array_push($return, $row);
}
return $return;
}
So then all you have to do is this in your script:
// connect to db, fill in the appropriate arguments...
$link = mysql_connect(...);
// selecting database
mysql_select_db($dbname, $link);
// do the query
$rows = my_query(...);
foreach($rows as $row){
print_r($row); // see what's in there...
}
By using the my_query() function, you save yourself a few steps. This is also particularly useful doing nested queries within loops. What's easier to read?
// assume database is already connected
$result = mysql_query('SELECT user_id FROM table');
while($row = mysql_fetch_object($result)){
$result_2 = mysql_query('SELECT * FROM other_table WHERE user_id = '.$row->user_id);
while($row_2 = mysql_fetch_object($result_2)){
// do stuff with both rows
// potential for lots of confusion and mysql errors
}
}
or this...
// assume database is already connected
$user_ids = my_query('SELECT user_id FROM table');
foreach($user_ids as $x){
$more_data = my_query('SELECT * FROM other_table WHERE user_id = '.$x->user_id);
foreach($more_data as $y){
// do stuff
}
}
Anyway, probably a much longer answered than you expected, but I hope it gives you an idea of how to go about things :) If you have time, install Wordpress and learn how to use its built in $wpdb object. You will gain a wealth of knowledge of how databases are used in real life applications and you'll be able to make your own database class to suit your needs.
DISCLAIMER: I just wrote all the above code for this post without testing for syntax errors. I apologize if there are any.
use:
while ($myrow = mysql_fetch_array($result))
{ ... }
it will work
I am working on a project needing me to work with multiple database connections. From what I have read, I should be able to switch between connections in the query itself, something like:
mysql_query("SELECT * FROM user_types", $db_core)or die(mysql_error());
But I receive the error:
Table 'db_company.user_types' doesn't exist
So I can see it is looking at the incorrect db, it is grabbing the last mysql_select_db
I wouldn't want to have to re-select the database everytime but if that is the better way to go I can.
I have the databases selected like so:
<?
$currentpage = $_SERVER["REQUEST_URI"];
//Core DB
$db_core_host = "localhost";
$db_core_username = "root";
$db_core_password = "";
$db_core_name = "db_main";
//
$db_core = mysql_connect($db_core_host,$db_core_username,$db_core_password);
mysql_select_db($db_core_name, $db_core)or die(mysql_error());
//Company DB
$db_company_host = $company['db_server'];
$db_company_username = $company['db_username'];
$db_company_password = $company['db_password'];
$db_company_name = $company['db_name'];
//
$db_company = mysql_connect($db_company_host,$db_company_username,$db_company_password);
mysql_select_db($db_company_name, $db_company)or die(mysql_error());
?>
Not sure if it helps at all but when I echo either of the database connections I get Resource id #5
Use the db.table syntax in the query:
mysql_query("SELECT * FROM databas_ename.table_name", $db_core) or die(mysql_error());
The code you have in your question should work, except when both databases are on the same server. Take a look at the $new_link parameter of mysql_connect (see docs here): if you call it twice with the same server/user/pass, the connection will be re-used - which makes you end up with the mysql_select_db call on one connection influence the other one.
So if you have two different servers, or set $new_link to true, your code should work.
For some reason, JavaScript/PHP wont delete my data from MySQL! Here is the rundown of the problem.
I have an array that displays all my MySQL entries in a nice format, with a button to delete the entry for each one individually. It looks like this:
<?php
include("login.php");
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("<br/><h1>Unable to connect to MySQL, please contact support at support#michalkopanski.com</h1>");
//select a database to work with
$selected = mysql_select_db($dbname, $dbhandle)
or die("Could not select database.");
//execute the SQL query and return records
if (!$result = mysql_query("SELECT `id`, `url` FROM `videos`"))
echo 'mysql error: '.mysql_error();
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
?>
<div class="video"><a class="<?php echo $row{'id'}; ?>" href="http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?>">http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?></a><a class="del" href="javascript:confirmation(<? echo $row['id']; ?>)">delete</a></div>
<?php }
//close the connection
mysql_close($dbhandle);
?>
The delete button has an href of javascript:confirmation(<? echo $row['id']; ?>) , so once you click on delete, it runs this:
<script type="text/javascript">
<!--
function confirmation(ID) {
var answer = confirm("Are you sure you want to delete this video?")
if (answer){
alert("Entry Deleted")
window.location = "delete.php?id="+ID;
}
else{
alert("No action taken")
}
}
//-->
</script>
The JavaScript should theoretically pass the 'ID' onto the page delete.php. That page looks like this (and I think this is where the problem is):
<?php
include ("login.php");
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
echo ("Video has been deleted.");
?>
If there's anyone out there that may know the answer to this, I would greatly appreciate it. I am also opened to suggestions (for those who aren't sure).
Thanks!
In your delete.php script, you are using this line :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
The $id variable doesn't exists : you must initialize it from the $_GET variable, like this :
$id = $_GET['id'];
(This is because your page is called using an HTTP GET request -- ie, parameters are passed in the URL)
Also, your query feels quite strange : what about this instead :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = '$id' ");
ie, removing the '.' : you are inside a string already, so there is nothing to concatenate (the dot operator in PHP is for concatenation of strings)
Note :
if this works on some server, it is probably because of register_globals
For more informations, see Using Register Globals
But note that this "feature" has been deprecated, and should definitely not be used !
It causes security risks
And should disappear in PHP 6 -- that'll be a nice change, even if it breaks a couple of old applications
your code has a big SQL injection hole : you should sanitize/filter/escape the $id before using it in a query !
If you video.id is a string, this means using mysql_real_escape_string
If you where using the mysqli or PDO extensions, you could also take a look at prepared statements
with an integer, you might call intval to make sure you actually get an integer.
So, in the end, I would say you should use something that looks like this :
$id = $_GET['id'];
$escaped_id = mysql_real_escape_string($id);
$query = "DELETE FROM `videos` WHERE `videos`.`id` = '$escaped_id'";
// Here, if needed, you can output the $query, for debugging purposes
mysql_query($query);
You're trying to delimit your query string very strangely... this is what you want:
mysql_query('DELETE FROM `videos` WHERE `videos`.`id` ='.$id);
But make sure you sanitize/validate $id before you query!
Edit: And as Pascal said, you need to assign $id = $_GET['id'];. I overlooked that.
In your delete.php you never set $id.
You need to check the value in $_REQUEST['id'] (or other global variable) and ONLY if it's an integer, set $id to that.
EDIT: Oh, also you need to remove the periods before and after $id in the query. You should print out your query so you can see what you're sending to the sql server. Also, you can get the SQL server's error message.
You add extra dots in the string.
Use
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='$id'");
instead of
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
Also check how do you get the value of $id.
Thanks everyone. I used Pascal MARTIN's answer, and it comes to show that I was missing the request ($_GET) to get the 'id' from the precious page, and that some of my query was incorrect.
Here is the working copy:
<?php
include ("login.php");
$id = $_GET['id'];
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = $id ");
echo ("Video ".$id." has been deleted.");
?>
Thanks again!