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');
Related
I have a successful connection to the database through this php script but it is not returning any values even though it is connected. I am checking for the results on my web browser and it just returns a blank screen. I have used the same script (different queries) to access two other tables in the database and they are both working fine. Here is my code:
<?php
$username = "xx";
$password = "xxx";
$host = "xxxxx";
$database="xxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
It is probably some silly mistake that I have over looked but I have been stuck on it for longer than I should! thanks in advance for any feedback
Tried you code locally on some data and it returns everything ok.
I needed to change the select to match my data
So I am 95% sure the problem is in your query / db settings.
I would first check if your columns in database is really called AUTHOR and 'In_order' with the exact capital letters.
MySql names can be case sensitive depending on your db server settings, and this could be the problem
Sidenote: if you can research mysqli and pdo for connecting to DB instead of mysql that is deprecated.
Try this:
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
$num = mysql_num_rows($query);
var_dump($query);
var_dump($num);
echo mysql_error();
and tell us what it all says.
Edit: okay, so it's 231 rows in your table, as the var_dump($num) says. Now let's try and get them at last, but in a slightly more efficient way:
while ($row = mysql_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
I have a feeling that your "for" loop and mysql_fetch_assoc() inside is what plays tricks with you, because both of them use different internal counters.
I am brand new to php/mysql, so please excuse my level of knowledge here, and feel free to direct me in a better direction, if what I am doing is out of date.
I am pulling in information from a database to fill in a landing page. The layout starts with an image on the left and a headline to the right. Here, I am using the query to retrieve a page headline text:
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row["banner_headline"];
}
?>
This works great, but now I want to duplicate that headline text inside the img alt tag. What is the best way to duplicate this queries information inside the alt tag? Is there any abbreviated code I can use for this, or is it better to just copy this code inside the alt tag and run it twice?
Thanks for any insight!
You are, as the comment says, using deprecated functions, but to answer your question, you should declare a variable to hold the value once your retrieve it from the database so that you can use it whenever your want.
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
$bannerHeadline = "";
while ($row = mysql_fetch_array($result)) {
$bannerHeadline = $row["banner_headline"];
}
echo $bannerHeadline; //use this wherever you want
?>
It is hard to help without knowing more. You are pumping the results into an array, are you expecting to only return one result or many banner_headline results? If you will only ever get one result then all you need to do is something like this:
PHP:
$result = mysql_query("
SELECT `banner_headline`
FROM `low_engagement`
WHERE `thread_segment` = 'a3'", $connection) or die(mysql_error());
// This will get the zero index, meaning first result only
$alt = mysql_result($result,0,"banner_headline");
HTML:
<html>
<body>
<!--- Rest of code -->
<img src="" alt="<?php echo $alt ?>">
On a side note, you should stop using mysql-* functions, they are deprecated.
You should look into PDO or mysqli
I have done a fair bit of research into what i want to do, although i haven't found anything. I am not too sure if i am looking for the right thing :( I am also a little bit new to PHP and MySQL syntax, so please be kind.
I wish to perform the following in this order:
Connect to a database (DONE)
Query for a specific string (I think im done)
From here is gets a bit fuzzy :(
If a match is found for the variable, copy the whole row (I need other variables).
Assign the values from the SQL query to a PHP variables.
From there i will be right to carry on.
I have established the connection to the database with the following:
function connect() {
$dbname = 'database';
$dbuser = 'username';
$dbpass = 'password';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
}
And then calling the function connect();
I then wish to query the database for a particular value, for the sake of this argument i will use a static value. This is what i have:
mysql_select_db(DATABASENAME) or die( "Unable to select database");
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'";
$result=mysql_query($query);
From here i am not too sure how to compare the query result to see if it is a match (something along the lines of mysql rows?).
If there is a match, then i would like to obtain the entire row, and assign each value to a php variable.
I am not asking for you to do it for me, simply i kick in the right direction should be fine!
Hope it explains it enough :)
Thanks for your kind guidance
Ok. You will want to keep the connection to the mysql database somewhere. A common use is $conn.
So you would have
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
Then, either from the URL or Post, or just some variables you have sitting in your php file, you can query the database by putting the variables in the query itself. Also, here you can use $conn so that you have one place to connect to the database, in an include for example, and you won't have to make all of the connection string in each place you need to connect to the DB.
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%" . $varToCompare . "%'";
$result=mysql_query($query,$conn);
Above you are using a like. You may want to just look at doing .. Where column=$var.
Then you can use php to spin through the results into an array (for queries where would get multiple rows).
Where the hell you learned how to use MySQL in PHP ? The mysql_* functions are more then 10 years old and not maintained anymore. Community has already begun to work on deprecating them.
You should be using PDO or MySQLi for that.
// connection to database
$db = new PDO('mysql:host=localhost;dbname=datadump_pwmgr;charset=UTF-8',
'datadump_pwmgr',
'kzddim05xrgl');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// setting up prepared statement for the query
$statement = $db->prepare('SELECT * FROM table WHERE column LIKE :value');
$statement->bindParam(':value', $some_variable, PDO::PARAM_STR, 127);
// executing query and fetching first result
if ( $statement->execute())
{
$data = $statement->fetch(PDO::FETCH_OBJ);
var_dump( $data );
}
This should give you something like what you needed. Though, I would recommend to try this tutorial. And learning more about prepared statements could be useful too.
Also , if you are working with objects, then it is possible to create a single DB connection object , and pass it to multiple other classes to use it:
$pdo = new PDO('sqlite::memory:');
$a = new Foo( $pdo );
$b = new Bar( $pdo, 'something');
This way you pass both objects the same database connection, and you do not need to reinitialize it.
I think you're looking for something like this:
$count = mysql_num_rows($result);
//if there is more then 1 record retrieved from the database
if($count > 0)
{
//Do what ever you want to do here, which I think you want to be
while ($row = mysql_fetch_assoc($result))
{
echo $row["Columnname1"];
echo $row["Columnname2"];
echo $row["Columnname3"];
}
}
else
{
echo "There are no matches for this specific value";
}
You can get the queried data by rows as an associated array using mysql_fetch_array():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_array($data)) !== false)
{
echo "row = $row, name1 = " . $result["name1"] . ", name2 = " . $result["name2"];
$row ++;
}
... or as an objects using mysql_fetch_object():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_object($data)) !== false)
{
echo "row = $row, name1 = $result->name1, name2 = $result->name2";
$row ++;
}
I'm not too sure of what you want, but I can see one probable bug here: you're using LIKE in a way which means =: in order to have LIKE to behave like a like, you need some joker chars :
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'" // This will return all rows where column='VAUL'
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'" // This will return all rows where column='%VAUL%' // This will return any row containing 'VAUL' in column
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE'" // This will return all rows where column='%VAUL' // this will return all rows ending by VAUL. I guess you get it now :)
An to retrieve the actual results:
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'";
$result=mysql_query($query);
while (false !== ($row = mysql_fetch_assoc($result))) {
//here $row is an array containing all the data from your mysql row
}
Try to write the database connection in another page no need to use function and include that page in where ever you need.
ex: require_once 'dbConnect.php';
dbConnect.php consists:
<?php
$dbname = 'datadump_pwmgr';
$dbuser = 'datadump_pwmgr';
$dbpass = 'kzddim05xrgl';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
?>
I would like to add results into array and print on screen.
Here's my code and nothing is printing...could someone help me take a look.
include('config.php');
$con = mysql_connect($host, $username, $password);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db('members', $con) or die(mysql_error()) ;
$sql = "SELECT * FROM people where status like '%married%' ";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$result_array[] = $row['id']; // <-------**here**
}
return $result_array;
echo($result_array);
mysql_close($con);
You're doing a return before you do the echo/mysql_close, so the echo/close calls never get executed. Unless you've got more code around this snippet, there's no point in having that return call, as you're not actually in a function, so the return is effectively acting as an "exit()" call, since you're already at the top of the execution stack.
Firstly, change:
mysql_select_db(mtar, $con) or die(mysql_error());
To:
mysql_select_db('mtar', $con) or die(mysql_error());
Then remove return $result_array; - you don't need it and when used outside of a function it just halts execution of the script.
Finally, change
echo($result_array);
to:
print_r($result_array);
EDIT: Some additional thoughts:
You don't need parentheses around the argument to echo - it's actually more efficient to leave them out: echo $var; is quicker than echo($var);
If you're only ever going to use the id column, then don't select the whole row: use SELECT id FROM instead of SELECT * FROM.
Are you sure you need the wildcards either side of "married"? You may well do (depends on what the possible values of status are), but you probably don't. So
$sql = "SELECT id FROM people where status = 'married' ";
May be better,
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.)