PHP - Create Table Function
Im messing around with functions and arrays but cant seem to get this to work. It basically creates a simple table with the parameters you specify. The array however doesnt go into the table properly.
function asf_create_table($rows, $cols, $border=1, $padding=5, $td_border=1, $contents) { $table = "<table style=\"border: {$border}px solid; padding:{$padding}px;\">"; for ($t_rows=0; $t_rows<$rows; $t_rows++) { $table .= "<tr>"; } for ($t_cols=0; $t_cols<$cols; $t_cols++) { for ($i=0; $i<$cols; $i++) { $table .= "<td style=\"border: {$td_border}px solid;\">"; $table .= $contents[$i]; $table .= "</td>"; } } for ($t_rows=0; $t_rows<$rows; $t_rows++) { $table .= "</tr>"; } $table .= "</table>"; echo $table; } $t_contents = array("Cell 1", "Cell 2", "Cell 3", "Cell 4"); asf_create_table("4", "4", "1", "5", "1", $t_contents); instead of 4 cells each with Cell # in them i get 16 cells with the cell #. the 4 displayed 4 times. Similar TutorialsHI All, I would like create query when I add some one is look what the last number in field and add one ? example : you can see the img in attach IDT is primary key + auto increment Customer_id is number field customer _name is name how can create this login IDT Customer_ID Customer_name 112 5 bbbb 113 6 ccccc 114 7 eeeee Also I need the inster function and is look the last field in customer_ID and Increase one ( +1) Any help please/ THanks Looking for help writing a function that does the following: Look for http:// or https:// in a string and replaces it with an <a href> tag. For example: Here is my link http://www.mydomain.com some further text here. Becomes: Here is my link <a href="http://www.mydomain.com">http://www.mydomain.com</a> some further text here. I have a table in my database for users. On the registration page I want to create another table with the id of the user as the table name. $sql = "CREATE TABLE IF NOT EXISTS `id_prod` ( ) how do i modify this line so that it takes the id from the user table and creates a new table with id as name followed by prod. For the life of me I can not figure out why this is not creating the table in the database. Second set of eyes would be great.
function install_kudos() { global $wpdb; $table_name = $wpdb->prefix . 'acikudosnew'; if ($wpdb->get_var('SHOW TABLES LIKE ' .$table_name) != $table_name) { $sql = "CREATE TABLE $table_name ( kudoid int(9) NOT NULL AUTO_INCREMENT, kudomsg text NOT NULL, kudoagent text NON NULL, kudocust text NOT NULL, kudoacct int(16) NOT NULL, kudoclient varchar(100) NOT NULL, kudoloc text NOT NULL, kudoentry TIMESTAMP DEFAULT CURRENT_TIMESTAMP, kudoadmin text NOT NULL, kudopic varchar(55) DEFAULT '' NOT NULL, PRIMARY KEY (kudoid) )"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } } register_activation_hook(__FILE__, 'install_kudos');
Here is function that backup mysql database. It's working fine, but I want to download file instead of creating it. /* backup the db OR just a table */ function backup_tables($host,$user,$pass,$name,$tables = '*') { $link = mysql_connect($host,$user,$pass); mysql_select_db($name,$link); //get all of the tables if($tables == '*') { $tables = array(); $result = mysql_query('SHOW TABLES'); while($row = mysql_fetch_row($result)) { $tables[] = $row[0]; } } else { $tables = is_array($tables) ? $tables : explode(',',$tables); } //cycle through foreach($tables as $table) { $result = mysql_query('SELECT * FROM '.$table); $num_fields = mysql_num_fields($result); $return.= 'DROP TABLE '.$table.';'; $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table)); $return.= "\n\n".$row2[1].";\n\n"; for ($i = 0; $i < $num_fields; $i++) { while($row = mysql_fetch_row($result)) { $return.= 'INSERT INTO '.$table.' VALUES('; for($j=0; $j<$num_fields; $j++) { $row[$j] = addslashes($row[$j]); $row[$j] = str_replace("\n","\\n",$row[$j]); if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; } if ($j<($num_fields-1)) { $return.= ','; } } $return.= ");\n"; } } $return.="\n\n\n"; } //save file $date= date("d-M-Y_h-i"); $handle = fopen('Backup-'.$date.'.sql','w+'); fwrite($handle,$return); fclose($handle); } Usage: Quote backup_tables('HOST','USER','PASS','TABLE'); But this will create backup file on server. I also tried to add following code in function (at the end): echo $return; header('Content-type: text/plain'); header("Content-Disposition: attachment; filename=\"$filename\""); How to just download file, without showing it on screen instead of using fwrite/fclose function? Hello, please let me know how to write xml file, i read somewhere we can use psql.....anyone knows please help! Thanks Code: [Select] <? $link = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Could not connect: ' . mysql_error()); mysql_select_db($dbname) or die ('Error connecting to database'); $sql = "SELECT * FROM papers WHERE ctitle='May 2012'"; $result = mysql_query($sql); $num = mysql_num_rows($result); //number of entry $data = mysql_query("select * from papers where ctitle='May 2012' ORDER BY id ASC"); $Wrd = new COM("Word.Application"); $Wrd->Application->Visible = False; $DocName = "MyDoc/MyWord.doc"; $WrdDoc = $Wrd->Documents->Add(); $WTable = $WrdDoc->Tables->Add($Wrd->Selection->Range, 2, $num); // Colums, Rows while($info=mysql_fetch_array($data)) { $i=1; $WTable->Cell($i,1)->Range->Text = $info['title']; $WTable->Cell($i,2)->Range->Text = $info['name'] $info['surname'] $info['institution'] $info['country']; $i++; } $Wrd->ActiveDocument->SaveAs(realpath($DocName)); $Wrd->Application->Quit; $Wrd = null; ?> Word Created <a href="<?=$DocName?>">Click here</a> to Download. php script is not working. Can someone please help me to detect the errors? i want create a table in ms word file for all entry in my database... "2 columns, number of rows" Cell(1,1) Cell(1,2) Cell(2,1) Cell(2,2) etc... Cell(3,1) Cell(3,2) i'm trying to achive this results layout: example: catagory comment comment comment catagory catagory catagory comment what is being pulled now is if their is 2 comments two 1 catagory then 2 catagorys are being returned with the same id. what i want is to return one cataogry with many comments. thanks in advance for your help. Code: [Select] <?php require_once('Connections/Del_Comments.php'); ?> <?php $all_ids = array(); $str_ids = ""; // first parent query $maxRows_sourceType = 10; $pageNum_sourceType = 0; if (isset($_GET['pageNum_sourceType'])) { $pageNum_sourceType = $_GET['pageNum_sourceType']; } $startRow_sourceType = $pageNum_sourceType * $maxRows_sourceType; mysql_select_db($database_Del_Comments, $Del_Comments); $query_sourceType = "SELECT a.Id, a.Type, a.Dates, a.UIdFk, b.Id as Did, b.comment, b.dates as Day, b.sfk as Sfk , c.sfk as sfk1, d.Memo as memo FROM asstatusupdate as a left join asstatusdata as b on a.id = b.sfk left join asmanystatusupdate as c on b.sfk = c.sfk left join ascomments as d on d.id = c.cfk where a.uidfk='1' order by Dates asc"; $query_limit_sourceType = sprintf("%s LIMIT %d, %d", $query_sourceType, $startRow_sourceType, $maxRows_sourceType); $sourceType = mysql_query($query_limit_sourceType, $Del_Comments) or die(mysql_error()); $row_sourceType = mysql_fetch_assoc($sourceType); if (isset($_GET['totalRows_sourceType'])) { $totalRows_sourceType = $_GET['totalRows_sourceType']; } else { $all_sourceType = mysql_query($query_sourceType); $totalRows_sourceType = mysql_num_rows($all_sourceType); } $totalPages_sourceType = ceil($totalRows_sourceType/$maxRows_sourceType)-1; // add the array while ($row_source = mysql_fetch_assoc($sourceType)) { $all_ids[] = $row_source['Sfk']; $str_ids .= $row_source['Sfk'].','; } // remove the array $str_ids = (substr($str_ids,-1) == ',') ? substr($str_ids, 0, -1) : $str_ids; echo $str_ids; //echo $all_ids; //second child query $maxRows_sourceComments = 10; $pageNum_sourceComments = 0; if (isset($_GET['pageNum_sourceComments'])) { $pageNum_sourceComments = $_GET['pageNum_sourceComments']; } $startRow_sourceComments = $pageNum_sourceComments * $maxRows_sourceComments; mysql_select_db($database_Del_Comments, $Del_Comments); $query_sourceComments = "SELECT c.sfk as sfk1, d.Memo as memo FROM asmanystatusupdate as c left join ascomments as d on d.id = c.cfk where c.uidfk0='1' and c.sfk in ($str_ids)"; $query_limit_sourceComments = sprintf("%s LIMIT %d, %d", $query_sourceComments, $startRow_sourceComments, $maxRows_sourceComments); $sourceComments = mysql_query($query_limit_sourceComments, $Del_Comments) or die(mysql_error()); $row_sourceComments = mysql_fetch_assoc($sourceComments); if (isset($_GET['totalRows_sourceComments'])) { $totalRows_sourceComments = $_GET['totalRows_sourceComments']; } else { $all_sourceComments = mysql_query($query_sourceComments); $totalRows_sourceComments = mysql_num_rows($all_sourceComments); } $totalPages_sourceComments = ceil($totalRows_sourceComments/$maxRows_sourceComments)-1; $resultComments = @mysql_query($query_sourceComments, $Del_Comments); $numComments = @mysql_num_rows($resultComments); $result = @mysql_query($query_sourceType, $Del_Comments); $num = @mysql_num_rows($result); // column count for parent $thumbcols = 1; // column count for parent query $thumbrows = 1+ round($num / $thumbcols); // column count for child query $thumbrowsComments = 1+ round($numComments/$thumbcols); // header print '<br />'; print '<table align="center" width="500" border="3" cellpadding="0" cellspacing="0">'; if (!empty($num)) { print '<tr><td colspan="3" align="center"><strong>Returned Num of Record Sets: ' .$num. ' and comments count' .$numComments. '</strong></td></tr>'; } // table layout for parent query function display_table() { // global variables global $num, $result, $thumbrows, $thumbcols, $resultComments, $numComments, $thumbrowsComments ; // row count for parent for ($r=1; $r<=$thumbrows; $r++) { // print table row print '<tr>'; //format the columns for ($c=1; $c<=$thumbcols; $c++) { print '<td align="center" valign="top">'; $row = @mysql_fetch_array($result); $row1 = @mysql_fetch_array($resultComments); $Id = $row['Id']; $Type = $row['Type']; $Dates = $row['Dates']; $Comment = $row['Comment']; $Sfk1 = $row['sfk1']; $Memo = $row['memo']; // test if not empty show record sets if (!empty($Id)) { // print output from parent query // grab type dates comment and format for there column echo '<td valign="top" align="center">'; echo "$Type"; echo ' '; echo "$Dates"; echo '<br />';echo '<br />';echo '<br />'; echo "$Comment"; echo '</td>'; echo '<td>'; echo "$Id"; echo '</td>'; echo '<td>'; echo "$str_ids"; echo '</td>'; echo '<tr>'; echo '<td>'; echo "$Sfk1"; echo '</td>'; echo '<td>'; echo "$Memo"; echo '</td>'; echo '</tr>'; } // closing the $id loop else { print ' '; } print '</td>'; //closing the table data } //closing the rows print '</tr>'; } // closing the outter loop //} //closing fk id loop print '</td>'; //closing the table data } //closing the rows print '</tr>'; //} // closing the main loop // call the main table display_table() ; print '</table>'; ?> <?php var_dump(substr('a', 1)); // bool(false) ?> Had some great help yesterday, but I'm stuck using <?php ?> on every line, thanks to Joomla Anyway, I'm trying to create a table, and it doesn't seem to be working, to create it, what is the correct format? <?php <table width='400px' border ='1'>; ?> ?? output will be put out on a per line within a if statement, which works, just the framing of the table and tr and td seem to be eluding me. Thanks I want to show a table with a max of three columns. I am using an if statement to count the rows and then start a new row (after 3 cols), I cant see my error. The output just gice one col with all the data in it. Any help appreciated. Code: [Select] <form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST" id="cover" enctype="multipart/form-data"> <table width="700"><?php /* display picture and radio button */ //add counter for more than 3 images $i=0; $size=3; while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $coverID=$row['coverID']; echo"<tr>"; echo "<td>"; echo"<img src=\"/wordpress_3/wp-content/plugins/Authors2/jackets/{$row['pix']}\" />"; echo "<input type = 'radio' name ='cover' value= '$coverID'/>"; ?> <br /> <input type="submit" value="submit"> <?php echo"</td>"; $i++; if($i==$size) { echo "</tr><tr>"; $i=0; } } ?></table> </form><?php Hi, I need a quick tip. I want this script to produce an output of "Table created" if it succesfully creates a table. <?php $con = mysql_connect("localhost","****","****"); if (!$con) { die('Could not connect: ' . mysql_error()); } // Create table mysql_select_db("my_db", $con); $sql = "CREATE TABLE People ( FirstName varchar(15), LastName varchar(15), Age int )"; // Execute query mysql_query($sql,$con); mysql_close($con); ?> I tried to do it on my own, but I guess I'm still completely new to php I tried: <?php $con = mysql_connect("localhost","****","****"); if (!$con) { die('Could not connect: ' . mysql_error()); } // Create table if (mysql_select_db("my_db", $con)) { echo "Table created"; } else { echo "Error creating Table: " . mysql_error(); } $sql = "CREATE TABLE People ( FirstName varchar(15), LastName varchar(15), Age int )" // Execute query mysql_query($sql,$con); mysql_close($con); ?> It gave me an error with the last two lines mysql_query($sql,$con); mysql_close($con); I removed them and it really did give the output "Table created" yet it didn't create the table in the database. I'm having a feeling that I need to add an "if" statement, something of the sort. if (sql(CREATE TABLE Persons)) But I'm also getting the feeling something there is wrong, I still haven't tried it. Help? Hey yall! I'm working on a new site idea and I've run across a problem that I know is simple enough but I'm stumped. It's in the signup form What I want to do is insert the new user into the 'Login' table and get the user id that was just created and use that to create a table with the user id in the name. Here is what I have: // now we insert user into 'Login' table mysql_real_escape_string($insert = "INSERT INTO `Login` (`UID`, `pass`, `HR`, `mail`, `FullName`) VALUES ('{$_POST['username']}', '{$_POST['pass']}', '{$_POST['pass2']}', '{$_POST['e-mail']}', '{$_POST['FullName']}')"); mysql_query($insert) or die( 'Query string: ' . $insert . '<br />Produced an error: ' . mysql_error() . '<br />' ); $error="Thank you, you have been registered."; setcookie('Errors', $error, time()+20); // Get user ID mysql_real_escape_string($checkID = "SELECT * FROM Login WHERE `mail` = '{$_POST['e-mail']}'"); while ($checkIDdata = mysql_fetch_assoc($checkID)) { $userID = $checkIDdata; // now we create table 'Transactions" for the user mysql_real_escape_string($create = "CREATE TABLE `financewatsonn`.`Transactions_{$userID}` ( `ID` INT( 20 ) NOT NULL AUTO_INCREMENT COMMENT 'Transaction ID', `name` VARCHAR( 50 ) NOT NULL COMMENT 'Name/Location', `amount` VARCHAR( 50 ) NOT NULL COMMENT 'Amount', `date` VARCHAR( 50 ) NOT NULL COMMENT 'Date', `category` VARCHAR( 50 ) DEFAULT NULL COMMENT 'Category', `delete` INT( 1 ) NOT NULL DEFAULT '0', UNIQUE KEY `ID` ( `ID` ) ) ENGINE = MYISAM DEFAULT CHARSET = utf8 COMMENT = 'User ID {$userID}'"); mysql_query($create) or die( 'Query string: ' . $create . '<br />Produced an error: ' . mysql_error() . '<br />' ); } I know in 'Get user ID' that I need to get the ID but I'm not sure how to get that information. i get the error Quote Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource at 166 which is the while line under Get user ID What I mean by dynamic is say I created a function to generate a random code. I put it in a variable named $key. I make a form with a hidden input type with the name and value of $key. When the form posts, it generates the table name to whatever $key is. Because I tried something like this & its not querying. Heres my code: <?php $dbc = mysqli_connect('localhost', 'cpacrop_todo', 'pass', 'cpacrop_todo') or die('Failed to connect to database!'); function make_key($num_chars) { if ((is_numeric($num_chars)) && ($num_chars > 0) && (! is_null($num_chars))) { $key = ''; $accepted_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; //seed srand(((int)((double)microtime()*1000003)) ); for ($i=0; $i<=$num_chars; $i++) { $random_number = rand(0, (strlen($accepted_chars) -1)); $key .= $accepted_chars[$random_number] ; } return $key; } } $key = make_key(6); ?> <form action="" method="post"> <input type="hidden" name="<?php echo "$key"; ?>" /> <input type="submit" name="submit" value="Submit" /> </form> <?php if ($_POST['submit'] == "Submit") { $query = "CREATE TABLE `$key` ( `id` INT AUTO_INCREMENT, `title` VARCHAR(35), `description` VARCHAR(365) );"; mysqli_query($dbc,$query) or die('Unable to query database.'); echo "Success"; } ?> If this is possible, what am I doing wrong? Thanks! Dear All, As I would like to create json as below format { "data": [ { "title": "After getting a COVID-19 Vaccine", "content": [ { "list": "You may have some side effects, which are normal signs that your body is building protection." }, { "list": "Following symptoms can take place, and it usually resolves within 2 to 3 days." }, { "list": "Common Side Effects pain, redness, swelling, warmth, nausea, muscle pain, tiredness, headache" } ] }, { "title": "After getting a COVID-19 Vaccine", "content": [ { "list": "You may have some side effects, which are normal signs that your body is building protection." }, { "list": "Following symptoms can take place, and it usually resolves within 2 to 3 days." }, { "list": "Common Side Effects pain, redness, swelling, warmth, nausea, muscle pain, tiredness, headache" } ] } ] } The information is from mysql select command: SELECT (tb_helpinfo.title_eng) as title,(tb_helpdetail.content_eng) as content FROM tb_helpinfo INNER JOIN tb_helpdetail ON tb_helpinfo.id = tb_helpdetail.helpinfo_id
i m tryin to create table from mysql coding and when i run the script its runs without any errors and just show that its created table but whn i chk into phpmyadmin i cnt find my table there and also when i use some copy paste from some website its just do the same thing but this time table is created but i cant find any difference between my table and the website table but still my script wont work please help me where is the mistake $connection=mysql_connect("127.0.0.1","root",""); $db=mysql_select_db("addressbook",$connection); if($db){ $SQL="CREATE TABLE address_data_new { ID int(7) NOT NULL auto_increment, First_name varchar(50) NOT NULL, ################## MY SCRIPT################ Last_name varchar(50) NOT NULL, email varchar(50) NOT NULL, PRIMARY KEY (ID), UNIQUE Id (ID) }"; /* $SQL="create table address_data { ID int(7) NOT NULL auto_increment, ############# working script############ First_Name varchar(50) NOT NULL, Surname varchar(50) NOT NULL, email varchar(50), PRIMARY KEY (ID), UNIQUE id (ID) )"; */ mysql_query($SQL); mysql_close($connection); echo "table added successfully"; } else { echo "database not found"; } ?> This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355753.0 Hello
I have a mysql table like this:
id | user | car 1 | 1 | fiat 500 2 | 2 | vw polo 3 | 2 | vw golf 4 | 3 | renault clio 5 | 2 | fiat panda 6 | 3 | seat ibiza From this table how can i get a query that the result be like: user 2 - 3 cars user 3 - 2 cars user 1 - 1 cars Thanks This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=355885.0 Have any of you ever run into this one. Can't quite figure this one out.
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE cUserID INT; DECLARE done INT DEFAULT FALSE; DECLARE CUR1 CURSOR FOR ' at line 9
I do have a sql table named "module" and a parent module may have a sub module. Each parent module can have a maximum of 9 sub modules of three per <td>. This is how this "module" table looks like: +-----------+------------------+----------+------+--------+---------------------+ | module_id | name | page_url | icon | parent | created_date | +-----------+------------------+----------+------+--------+---------------------+ | 1 | User Modules | | NULL | NULL | 2021-07-21 11:46:16 | | 2 | Items | | NULL | 1 | 2021-07-21 11:46:16 | | 3 | Add New Item | | NULL | 2 | 2021-07-21 11:46:16 | | 4 | View Item | | NULL | 2 | 2021-07-21 11:46:16 | | 5 | Category | | NULL | 2 | 2021-07-21 11:46:16 | | 6 | Brand | | NULL | 2 | 2021-07-21 11:46:16 | | 7 | Unit | | NULL | 2 | 2021-07-21 11:46:16 | | 8 | Purchase | | NULL | 1 | 2021-07-21 11:46:16 | | 9 | Add New Purchase | | NULL | 8 | 2021-07-21 11:46:16 | | 10 | view Purchase | | NULL | 8 | 2021-07-21 11:46:16 | | 11 | Due Invoice | | NULL | 8 | 2021-07-21 11:46:16 | | 12 | Return | | NULL | 8 | 2021-07-21 11:46:16 | | 13 | Purchase Log | | NULL | 8 | 2021-07-21 11:46:16 | | 14 | Inventory | | NULL | 1 | 2021-07-21 11:46:16 | | 15 | Stock Transfer | | NULL | 14 | 2021-07-21 11:46:16 | | 16 | Stock Adjustment | | NULL | 14 | 2021-07-21 11:46:16 | | 17 | Batch Control | | NULL | 14 | 2021-07-21 11:46:16 | | 18 | Stock Take | | NULL | 14 | 2021-07-21 11:46:16 | +-----------+------------------+----------+------+--------+---------------------+ My desired HTML table layout looks somthing similar to this attach image.
I would like to know how we can do it in php, if is possible. Thank you. Edited July 23 by thara |