Bulk update to mySQL work too slow - mysql

currenly i use a simple code to update gender in my mysql
my code:
<?php
ini_set('max_execution_time', 30000);
$row = 0;
if (($handle = fopen("list.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$name = $data[0];
$gender = $data[1];
}
// connect to db
mysql_connect("***", "***", "***") or die("Connection Failed");
mysql_select_db("info")or die("Connection Failed");
$query = "UPDATE data SET gender = '$gender' WHERE fname = '$name'";
if(mysql_query($query)){
$row++;
echo "$row: ";
echo '<font color="RED">' . $name . '</font> <br>';
}
}
fclose($handle);
}
?>
code works but very slow,
can process up to 10k records per 1 hour and its too slow for me
can someone give me an idea what to do with it to increase speed

You are re-connecting to the DB in every single while iteration. Take the mysql_connect and mysql_select_db calls out of the while loop...

Related

WordPress and PHP | Check if row exists in database if yes don't insert data

I'm fairly new to WordPress and SQL. I have a contact form that I want to have the data be submitted to my WordPress database but only if the data that has been entered has not been entered before.
This is what i have so far, which sends data to my database when form is submitted.
if(isset($_POST['contact_us'])) {
$invalidContact = "<h5 class='invalidBooking'> Nope try again</h5>";
$successContact = "<h5 class='invalidBooking'> Message Sent!</h5>";
$table_name='contact_table';
global $wpdb;
$contact_name = esc_attr($_POST['contact_name']);
$contact_email = sanitize_email($_POST['contact_email']);
$subject = esc_attr($_POST['subject']);
$message = esc_attr($_POST['message']);
$error= array();
if (empty($contact_name)) {
$error['name_invalid']= "Name required";
}
if (empty($contact_email)){
$error['email_invaild']= "Email required";
}
// Im guessing some code here to check if row exists in database
if (count($error) >= 1) {
echo $invalid;
}
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
echo $successContact;
}
}
You may try this code
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$query = "SELECT * FROM $table_name WHERE 'Contact_Name'= '$contact_name' AND 'Contact_Email' = '$contact_email' AND 'Contact_Subject' = '$subject' AND 'Contact_Message' = '$message'";
$query_results = $wpdb->get_results($query);
if(count($query_results) == 0) {
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
}
}
Hope this works for you.
fetch data using this code
$query = "SELECT * FROM {$wpdb->prefix}table WHERE column = 1";
echo $query;
$results = $wpdb->get_results($query);
and then you know what to do...

i have issue with my database mySQL select from table

Dears
Please help me in this matter.
I have issue with my MySQL database.
It is working fine if I'm doing inserting records to the table. However, if I'm doing selecting and fetching, the result is 0 despite of the table actually have records.
$sql2 = 'SELECT * FROM `users`';
$result2 = $conn->query($sql2);
echo $result2->num_rows;
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
please help me guys I tried every thing I almost give up.
thanks,
Maybe you can try this code
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=contoh', "root", "root");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql2 = 'SELECT * FROM `user_ranks`';
$result2 = $conn->query($sql2);
while($row = $result2->fetch()) {
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
}
}
catch (PDOException $e) {
print "connection or query have a problem: " . $e->getMessage() . "<br/>";
die();
}

How to fetch single row/data from Mysql_fetch_array?

I am reading .csv file through PHP using fgetcsv(). Now I am able to fetch I mean read data from .csv file.
Then I need to check SKU column with my fetch result & accordingly have to perform either Insertion Or Updation.
Suppose SKU is already present there, then I have to update my row in table else I need to insert new record.
I have write following code...Plz check n tell me where I am doing mistake-:
<?php
$row = 1;
if (($handle = fopen("localhost/data/htdocs/magento/var/import/Price.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 8000, ",")) !== FALSE)
{
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
for ($c=0; $c < $num; $c++)
{
$temp = $data;
$string = implode(";", $temp);
}
$pieces = explode(";", $string);
$col1 = $pieces[0];
$col2 = $pieces[1];
$col3 = $pieces[2];
$col4 = $pieces[3];
$db_name = "magento";
$con = mysql_connect("localhost", "magento", "password");
If (!$con)
{
die('Could not connect: ' . mysql_error());
mysql_close($con);
}
$seldb = mysql_select_db($db_name, $con);
$query_fetch = "SELECT `sku` from `imoprt_prices`";
$result_fetch = mysql_query($query_fetch);
$num_rows = mysql_num_rows($result_fetch);
for($i = 0; $i < $num_rows; $i++)
{
$value = mysql_result($result_fetch, i, 'sku');
if(strcmp('".$value."', '".$col2."') == 0)
{
$flag = 1;
break;
}
else
{
$flag = 0;
break;
}
}
if($flag == 1)
{
$query_upadte = "(UPDATE imoprt_prices SET customer_id= '".$col1."', sku ='".$col2."', price= '".$col3."', website= '".$col4."'
)";
mysql_query($query_upadte);
$row++;
}
if($flag == 0)
{
mysql_query("INSERT INTO `imoprt_prices`(`customer_id`,`sku`,`price`,`website`) VALUES('".$col1."','".$col2."','".$col3."','".$col4."')");
$row++;
}
}
}
?>
If you have an actual UNIQUE index on your imoprt_prices table, you can use the ON DUPLICATE KEY UPDATE syntax and simplify your code a bit to something similar to; (note, can't test, so see as pseudo code)
$db_name = "magento";
$con = mysql_connect("localhost", "magento", "password") or die(mysql_error());
$seldb = mysql_select_db($db_name, $con);
if (($handle = fopen("localhost/data/htdocs/magento/var/import/Price.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 8000, ",")) !== FALSE)
{
$col1 = $pieces[0];
$col2 = $pieces[1];
$col3 = $pieces[2];
$col4 = $pieces[3];
$query_upadte = "INSERT INTO imoprt_prices (customer_id, sku, price, website) ".
"VALUES('".$col1."','".$col2."','".$col3."','".$col4."') ".
"ON DUPLICATE KEY UPDATE customer_id='".$col1."', price='".$col3.
"',website='".$col4."'";
mysql_query($query_upadte);
}
}
You may also want to either mysql_real_escape_string() or use parameterized queries to make sure there's no ' in your inserted values though. That is always a danger with building sql strings like this.
Simple demo here.
In the following snippet:
$query_upadte = "UPDATE imoprt_prices SET customer_id= '".$col1."', sku ='".$col2."', price= '".$col3."', website= '".$col4."'";
You're trying to update all the rows repeatedly, instead of just updating a single row. This is normally not allowed in MySQL. You need to specify a particular unique ID to be updated.

Storing database structure

Is there some tool that can store for me the database structure, say in some xml file or something like that.
And later from the code it can generate for me the sql query for this database creation ?
Currently I am working with MySQL , but it probably does not matter .
Just I not want to maintain my self all those things.
In my experience I have used MySQL Workbench to take care of issues like this. If you download Workbench (assuming you don't have it already) from http://wb.mysql.com/ you will have the option to "Create an EER diagram from an existing database." This will create an EER diagram which is a good visual presentation of the database with which you are working. The .mwb file that you can then save can be loaded and then "forward engineered" into local/external database.
Mysqldump is another alternative to use at the command line. It will, by default, dump out the entire schema structure and contained data. However, if you are just looking for database structure including views and routines and you do not care about the data itself then you need to throw some extra parameters into the command.
In my experience Mysqldump is quick and easy whereas EER diagrams are easier to share with others and then forward engineer back onto other DBs from the Workbench application.
EDIT
You should note that just because you export the database create table queries to a .sql file or .mwb file that you can't just copy and paste the text into another platform (Microsoft SQL, Oracle, etc) and expect it to work. Syntax across different versions of SQL is (obviously) different.
THE FOLLOWING ANSWER USES PHP, I am keeping it here for future users.
I wrote code specifically to do that (in PHP):
$db = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
$allTables = Array
(
//put all table names in this array
);
foreach($allTables as $tbl){
define($tbl, $tbl);
}
$clm = '$columns';
$inds = '$indexes';
$query = "SHOW TABLES IN {$dbname}";
$tables = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$tables[] = $row["Tables_in_{$dbname}"];
}
//TO GET ARRAY FOR TABLE DISPLAY:
$cols = array();
foreach($tables as $tbl){
// echo "<br/>".
$query = "SHOW COLUMNS FROM $tbl";
$cols[$tbl] = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$cols[$tbl][] = array('Field'=>$row['Field'],
'Type'=>$row['Type'],
'Null'=>$row['Null'],
'Default'=>$row['Default'],
'Extra'=>$row['Extra'],
);
}
}
$index = array();
$query = "SELECT * FROM information_schema.statistics
WHERE TABLE_SCHEMA = '{$dbname}';
";
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$index[$row['TABLE_NAME']][] = array('INDEX_NAME'=>$row['INDEX_NAME'],
'COLUMN_NAME'=>$row['COLUMN_NAME'],
'INDEX_TYPE'=>$row['INDEX_TYPE'],
'INDEX_NAME'=>$row['INDEX_NAME'],
'SEQ_IN_INDEX'=>$row['SEQ_IN_INDEX'],
);
}
//echo "<pre>";print_r($index);
//exit;
//TO GET THE ARRAY VARIABLE
echo "<pre>
<?php
$clm = Array (";
foreach ($cols as $key=>$tbl){
echo "
$key => Array (";
foreach($tbl as $col){
echo "
Array ( ";
foreach($col as $k=>$val){
echo "
'$k' => \"$val\",";
}
echo "
),";
}
echo "
),";
}
echo "
);";
echo "</pre>";
echo "<pre>
$inds = Array (";
foreach ($index as $key=>$tbl){
echo "
$key => Array (";
foreach($tbl as $col){
echo "
Array ( ";
foreach($col as $k=>$val){
echo "
'$k' => \"$val\",";
}
echo "
),";
}
echo "
),";
}
echo "
);
?>";
echo "</pre>";
Paste the result to this in a php file (called currentDB.php).
Then in another file is where the creation happens with the file you created:
define('BY_COL', 'column');
define('BY_IND', 'index');
$allTables = Array
(
//put all table names in this array
);
foreach($allTables as $tbl){
define($tbl, $tbl);
}
include_once 'currentDB.php';
$query = "SHOW TABLES IN $dbname";
$tables = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$tables[] = $row["Tables_in_$dbname"];
}
$checkTables = checkTables($tables);
echo "THE FOLLOWING TABLES <b>ARE</b> IN THE DB: <br />
<pre>";print_r(array_diff($allTables,$checkTables));echo "</pre><br />";
if($checkTables){
echo "THE FOLLOWING TABLES <b>ARE NOT</b> IN THE DB: <br />".
// "<pre>";print_r($checkTables);echo "</pre><br />";
"";
createTables($checkTables);
$query = "SHOW TABLES IN $dbname";
$tables = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$tables[] = $row["Tables_in_$dbname"];
}
}
//TO GET ARRAY FOR TABLE DISPLAY:
$cols = array();
foreach($tables as $tbl){
// echo "<br/>".
$query = "SHOW COLUMNS FROM $tbl";
$cols[$tbl] = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$cols[$tbl][] = array('Field'=>$row['Field'],
'Type'=>$row['Type'],
'Null'=>$row['Null'],
'Default'=>$row['Default'],
'Extra'=>$row['Extra'],
);
}
}
$checkTables = checkCols($cols);
if($checkTables){
echo "THE FOLLOWING COLS <b>ARE DIFFERENT</b> IN THE DB: <br />".
// "<pre>";print_r($checkTables);echo "</pre><br />".
"";
alterTable($checkTables);
}
$index = array();
$query = "SELECT * FROM information_schema.statistics
WHERE TABLE_SCHEMA = '$dbname';
";
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$index[$row['TABLE_NAME']][] = array('INDEX_NAME'=>$row['INDEX_NAME'],
'COLUMN_NAME'=>$row['COLUMN_NAME'],
'INDEX_TYPE'=>$row['INDEX_TYPE'],
'INDEX_NAME'=>$row['INDEX_NAME'],
'SEQ_IN_INDEX'=>$row['SEQ_IN_INDEX'],
);
}
$checkTables = checkIndexes($index);
if($checkTables){
echo "THE FOLLOWING INDEXES <b>ARE DIFFERENT</b> IN THE DB: <br />".
// "<pre>";print_r($checkTables);echo "</pre><br />".
"";
alterTable($checkTables,BY_IND);
}
//echo "<pre>";print_r($indexes);echo "</pre><br />";
function checkTables($array){
$tbls = $GLOBALS['allTables'];
$diff = array_diff($tbls,$array);
if($diff){
return $diff;
}
return array();
}
function checkCols($array){
$cols = $GLOBALS['columns'];
$diff = array_diff_no_cast($cols,$array);
if($diff){
// echo "HI<br />";
return $diff;
}
return array();
}
function checkIndexes($array){
$ind = $GLOBALS['indexes'];
$diff = array_diff_no_cast($ind,$array);
if($diff){
// echo "HI<br />";
return $diff;
}
return array();
}
function createTables($tables){
$cols = $GLOBALS['columns'];
$ind = $GLOBALS['indexes'];
foreach($tables as $t){
$thisCols = (isset($cols[$t])?$cols[$t]:array());
$thisInd = (isset($ind[$t])?fromIndex($ind[$t]):array());
$create = "CREATE TABLE `$t` (\n";
foreach($thisCols as $k=>$c){
// echo "<pre>$k\n{$c['Default']}</pre>";
if($c['Default']=='CURRENT_TIMESTAMP'){
// echo "IN HERE";
$c['Extra'] = " ON UPDATE CURRENT_TIMESTAMP";
}
$create .= "`{$c['Field']}` {$c['Type']} ".
(($c['Null']=='NO')?'NOT NULL':'')." ".
((strlen($c['Default'])>0)?"DEFAULT ".
(is_quoted($c['Default'])?"'{$c['Default']}'":"{$c['Default']}"):'').
"{$c['Extra']}";
if(count($thisCols)!==($k+1)){
$create .= ",\n";
}
else
$create .= "\n";
}
$i = 0;
foreach($thisInd as $k=>$c){
if($i == 0){
$create .= ",\n";
}
if($c['INDEX_NAME']=='PRIMARY'){
$create .= "PRIMARY ";
}
else{
$iName = explode("_",$c['INDEX_NAME']);
if(array_search("UNIQUE",$iName)){
$create .= "UNIQUE ";
}
}
$create .= "KEY ".
(($c['INDEX_NAME']=='PRIMARY')?'':"`{$c['INDEX_NAME']}`")." ({$c['COLUMN_NAME']})";
if(count($thisInd)!==($i+1)){
$create .= ",\n";
}
else
$create .= "\n";
// echo "<pre>";print_r($c);echo "</pre>";
$i++;
}
$create .= ");";
// echo "<pre>$create</pre>";
mysql_query($create) or die("ERROR CREATE:".mysql_error());
echo "CREATED $t<br />";
}
// die;
}
function fromIndex($ind){
$return = array();
foreach($ind as $i){
$return[$i['INDEX_NAME']]['INDEX_NAME'] = $i['INDEX_NAME'];
// echo $i['COLUMN_NAME']." -- <br/>".
$return[$i['INDEX_NAME']]['COLUMN_NAME'] = (isset($return[$i['INDEX_NAME']]['COLUMN_NAME'])?"{$return[$i['INDEX_NAME']]['COLUMN_NAME']}, `{$i['COLUMN_NAME']}`":"`{$i['COLUMN_NAME']}`");
}
// echo "<pre>";print_r($return);echo "</pre>";
// die;
return $return;
}
function alterTable($table, $type = BY_COL){
// echo "<u>";
switch ($type){
case BY_COL:
// echo BY_COL;
$tbls = $GLOBALS['cols'];
$realTbls = $GLOBALS['columns'];
// echo "<pre>";print_r($table);echo"</pre>";
// die;
foreach($table as $k=>$t){
// echo
// $query = "SHOW COLUMNS FROM $k";
// echo "<br />";
foreach($t as $ky=>$col){
// echo
if($ky == 0){
$after = 'FIRST';
}
else {
$after = "AFTER `{$realTbls[$k][$ky-1]['Field']}`";
}
$primary = false;
if($col['Default']=='CURRENT_TIMETAMP'){
$col['Extra'] .= " ON UPDATE CURRENT_TIMESTAMP";
}
if($col['Extra'] == 'auto_increment'){
$query2 = "ALTER TABLE `$k` ADD PRIMARY KEY ( `{$col['Field']}` )";
$query3 = "ALTER TABLE `$k` CHANGE COLUMN `{$col['Field']}`
`{$col['Field']}` {$col['Type']} ".($col['Null']=='YES'?'NULL':'NOT NULL').
((!empty($col['Default']))? ' DEFAULT '.(is_quoted($col['Default'])?"'{$col['Default']}'":$col['Default']):'').
" {$col['Extra']}".
" $after;";
$primary = true;
$col['Extra'] = "";
}
// echo
$query = "ALTER TABLE `$k` ".(field_in_array($tbls[$k],$col['Field'])?"CHANGE COLUMN `{$col['Field']}`":"ADD COLUMN").
" `{$col['Field']}` {$col['Type']} ".($col['Null']=='YES'?'NULL':'NOT NULL').
((!empty($col['Default']))? ' DEFAULT '.(is_quoted($col['Default'])?"'{$col['Default']}'":$col['Default']):'').
" {$col['Extra']}".
" $after;";
// echo "<br/>";
mysql_query($query) or die("ERROR CREATE: $query".mysql_error());
if($primary){
mysql_query($query2) or die("ERROR CREATE: $query2".mysql_error());
mysql_query($query3) or die("ERROR CREATE: $query3".mysql_error());
}
echo "ADDED $k: {$col['Field']}";
echo "<br />";
}
// if($k == 'sessions'){
// echo "<pre>$ky:\n";print_r($tbls[$k]);die;
// }
}
break;
case BY_IND:
// echo BY_IND;
$tbls = $GLOBALS['index'];
foreach($table as $k=>$t){
$addTbls= fromIndex($table[$k]);
$thisInd = (isset($tbls[$k])?fromIndex($tbls[$k]):array());
// echo "<pre>$k:\n";print_r($addTbls);
foreach($addTbls as $added){
$beg = "INDEX";
if($added['INDEX_NAME']=='PRIMARY'){
$beg = "PRIMARY KEY";
$added['INDEX_NAME'] = '';
}
else{
$iName = explode("_",$added['INDEX_NAME']);
if(array_search("UNIQUE",$iName)){
$beg = "UNIQUE ".$beg;
}
}
// echo
$query = "ALTER TABLE `$k` ".(field_in_array($thisInd,$added['INDEX_NAME'],'INDEX_NAME')?"DROP INDEX `{$added['INDEX_NAME']}`, ":'')."ADD $beg `{$added['INDEX_NAME']}` ({$added['COLUMN_NAME']})";
mysql_query($query) or die("ERROR CREATE:".mysql_error());
echo "ADDED $k: {$added['INDEX_NAME']}";
echo "<br />";
}
}
// die;
break;
}
// echo "</u><br />";
}
function is_quoted($str){
if(is_numeric($str))
return false;
if($str == 'CURRENT_TIMESTAMP')
return false;
return true;
}
function field_in_array($arr, $field, $type = 'Field'){
foreach($arr as $val){
// echo "HERE: $field, $type";
// print_r($val);echo "<br/>";
if($val[$type]==$field){
// echo "HI";
return true;
}
}
return false;
}
##################################
# FUNCTION - multidim diff #
##################################
function array_diff_no_cast(&$ar1, &$ar2) {
$diff = Array();
foreach ($ar1 as $key => $val1) {
foreach($val1 as $k=>$val2){
if (!isset($ar2[$key]) || array_search($val2, $ar2[$key]) === false) {
$diff[$key][$k] = $val2;
}
}
}
return $diff;
}
You can export your database with Mysqldump. The web page has all the details on how to use it.
If you want the SQL to create the table, you can use:
SHOW CREATE TABLE tblname
If you have data, foreign keys, stored procedures and views in your database then the MySQL Workbench can forward reverse all that for you.
For MySQL and others, you might want to try the DESCRIBE TABLE.
You might want to look into the mysqldump utility. It will create a copy of your database in SQL format. (Note to avoid a problem I ran into: Be sure to run it with --routines if you want to also capture your stored functions and procedures!)
A typical command would look something like this:
mysqldump --routines -Q --opt -p -u username databasename >savefile.sql
Also, for large databases, these files can get quite large. You might also want to consider gzipping them or otherwise compressing them on the fly, using something like:
mysqldump --routines -Q --opt -p -u username databasename | gzip >savefile.sql.gz
use phpMyAdmin u can export your structure to XML,SQL,CSV and many other by using export option

PHP MySQL script gone wrong

I'm working on a site and created this experimental script which populates a category menu dynamically based on the database entry.
It worked for a day and then suddenly stopped. I changed my includes for requires and it gave me this error message
Fatal error: Maximum execution time of 30 seconds exceeded in /home1/advertbo/public_html/dev_area/origocloud/include/views/blog/dbget.php on line 34
function getBlogMenu(){
$dbhost = 'localhost';
$dbuser = ' ';
$dbpass = ' ';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ado_ocblog", $con);
$htmlString = "";
$result = mysql_query(
"SELECT *
FROM subCat
JOIN headCat ON subCat.headid = headCat.id
ORDER BY headid ASC;");
$array = mysql_fetch_array($result);
mysql_close($con);
$pre = NULL;
$hc = 0;
$sc = 1;
while ($array) {
if($pre == NULL){
$pre = $row["headc"];
$test[0][0]=$row["headc"];
$test[0][1]=$row["subc"];
}
else
{
if($pre ==$row["headc"]){
$sc++;
$test[$hc][$sc] = $row["subc"];
}
else
{
$hc++;
$sc = 1;
$test[$hc][0]=$row["headc"];
$test[$hc][$sc]=$row["subc"];
$pre = $row["headc"];
}
}
}
foreach( $test as $arrays=>$cat)
{
$first = TRUE;
foreach($cat as $element)
{
if($first == TRUE)
{
$htmlString.= '<h3>'.$element.'</h3>
<div>
<ul>
';
$first = FALSE;
}
else
{
$htmlString.= '<li><a class="sub_menu" href="#">'.$element.'</a></li>';
}
}
$htmlString.= '</ul> </div>';
}
return $htmlString;
}
I'm really stuck, the page just keeps timing out the point where i call the function
Try this:
while ($array = mysql_fetch_array($result)) {}
Take a look on PHP docs http://php.net/mysql_fetch_array
If does not work, your SQL Query returns too much values and craches the php execution
=]
I think it's time to take a step back and look at what you're doing :) This function should do what you want (even if you fixed the infinite loop problem in the function you gave, I don't think it would act how you want it to.):
function getBlogMenu(){
$dbhost = 'localhost';
$dbuser = ' ';
$dbpass = ' ';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ado_ocblog", $con);
$htmlString = "";
$result = mysql_query(
"SELECT *
FROM subCat
JOIN headCat ON subCat.headid = headCat.id
ORDER BY headid ASC;");
// arrays can have strings as keys as well as numbers,
// and setting $some_array[] = 'value'; (note the empty brackets [])
// automatically appends 'value' to the end of $some_array,
// so you don't have to keep track of or increment indexes
while ($row = mysql_fetch_assoc($result))
{
$test[$row["headc"]][] = $row["subc"];
}
// don't close the connection until after we're done reading the rows
mysql_close($con);
// $test looks like: array('headc1' => array('subc1', 'subc2', 'sub3'), 'headc2' => array('subc4', 'subc5'), ...)
// so we step through each headc, and within that loop, step through each headc's array of subc's.
foreach($test as $headc => $subc_array)
{
$htmlString.= '<h3>'.$headc.'</h3><div><ul>';
foreach($subc_array as $subc)
{
$htmlString.= '<li><a class="sub_menu" href="#">'.$subc.'</a></li>';
}
$htmlString.= '</ul></div>';
}
return $htmlString;
}