PHP - Can This Code Be Made Smoother?
Hi all,
I was playing a bit around with results from a database and thought lets give them a nice order in a table, so i thought i set the class per row, so my style sheet can finish it. This is what i got and it works. But some 6th sense whispers me that this can be done smoother. If anyone has ideas or tips let me know i have a lot to learn in php. and after all want to be a good code writer in php. // start table echo '<table class="users"> <th>name</th><th>email</th><th>active</th>'; $odd = 1; $num = 1; while($row = mysqli_fetch_assoc($result)){ // if( $odd == $num%2 ){ $evenodd = 'odd'; $num++; }else{ $evenodd = 'even'; $num++; } // echo'<tr class="'.$evenodd.'"><td>'.$row['name'].'</td><td>'.$row['email'].'</td><td>'.$row['accept'].'</td><tr>'; } echo '</table>'; thanks Similar TutorialsHi! I have started a big project with some of my friends. Its some kind of CMS system. Now, for quick commands we wanted something like cmd on windows. Is it possible to build a script that would be something like cmd/a console. Of course it would be a webpage and not a separate window. I could do this myself with a input field and a form using the POST method. But I wouldn't wan't to refresh the page every time I run a command. So something that works like the input field, form with the POST method, but without needing to refresh every time. Ask if I didn't make it clear enough! Regards Kevin
hello i am learning php a newbie .
// this is the user input / textdata
if(isset($_POST['textdata']))
// i added this line
// i changed this line below
fwrite($fp, $data);
thank you in advance. Edited November 21, 2019 by thehubclickleft out info I have this query that fully works the way it is, but I am wondering if I am overdoing some things in it. I know this may be hard to tell without knowing the full relationship between all the tables in the query. I'm basically running 3 subqueries mostly based on a timestamp value and other specific clauses per subquery. Where the main query is only gathering based on the timestamp.
Like I said it works perfect from what I can verify by cross referencing the tables manually and checking the results the query returned. I just want to know if there is a better way to do all this.
SELECT `products`.`id` AS `pid`, `products`.`prod_name`, (SELECT COUNT(*) FROM `products` INNER JOIN `quote_deposits` ON `quote_deposits`.`product_id` = `products`.`id` INNER JOIN `quote_responses` ON `quote_responses`.`id` = `quote_deposits`.`q_id` WHERE `quote_responses`.`purchased` = 0 AND `quote_deposits`.`dep_date` >= $committed_start ) AS `committed`, (SELECT COUNT(`products`.`id`) FROM `products` INNER JOIN `quote_deposits` ON `quote_deposits`.`product_id` = `products`.`id` INNER JOIN `quote_responses` ON `quote_responses`.`id` = `quote_deposits`.`q_id` WHERE `quote_responses`.`purchased` = 1 AND `products`.`id` = `pid` AND `quote_deposits`.`dep_date` >= $committed_start ) AS `total_per_item`, (SELECT COUNT(`products`.`id`) FROM `products` INNER JOIN `quote_deposits` ON `quote_deposits`.`product_id` = `products`.`id` INNER JOIN `quote_responses` ON `quote_responses`.`id` = `quote_deposits`.`q_id` INNER JOIN `schedule` ON `schedule`.`deposit_id` = `quote_deposits`.`id` WHERE `quote_responses`.`purchased` = 0 AND `schedule`.`cancelled` != '' AND `products`.`id` = `pid` AND `quote_deposits`.`dep_date` >= $committed_start ) AS `total_cancelled` FROM `products` INNER JOIN `quote_deposits` ON `quote_deposits`.`product_id` = `products`.`id` WHERE `quote_deposits`.`dep_date` >= $committed_start GROUP BY `products`.`prod_name` ORDER BY `products`.`prod_name` ASC Hey guys basically with a simple script that I made I need some help with it's doing my head in. What i'm trying to do is allow multiple filetypes to be shown by readdir, i want both .zip and .rar to be in the list, not just .zip how would i add .rar in this method as well to be visible on readdir? <?php $dirname = "/home/test/"; $dir = opendir($dirname); $extension = array_pop(explode(".", $file)); ?> <?php while(false != ($file = readdir($dir))) { if ($file != "." && $file != ".." && array_pop(explode(".", $file)) == "zip") { echo(" <b>» <a href='$dirname$file'>$file - Download</a> <br /> </b> "); } } ?> Hello everyone For a site of one of our customers our programmer created his own CMS which works OK at the site, but now the customer wants to shorten the URLS which are generated by the system. Is this easily possible? The programmer doesn't have the time to help us with it so that's why I try my luck here... I hope somebody can help me. Thanks! so I am about to start on a small object oriented project, for practice/learning etc. I have 5 files in a folder called "objects" : (obj1.php obj2.php obj3.php obj4.php obj5.php) . I then created a "classloader.php" with the following code: Code: [Select] <?php include "objects/obj1.php"; include "objects/obj2.php"; include "objects/obj3.php"; include "objects/obj4.php"; include "objects/obj5.php"; ?> and then finally my main page (for the sake of testing): Code: [Select] <!DOCTYPE HTML> <head> <title>...</title> </head> <?php include "classloader.php"; ?> <body> <header></header> <nav></nav> <section> <?php object1(); object2(); object3(); object4(); object5(); ?> </section> <footer></footer> </body> What is the best way to handle the loading of objects in php? I think I am doing it somewhat wrong. Anyone lend me some more info here? thanks much. Hello, Where can i find the source of the pre made php functions? Greets, Scuar.
Hello people! Well, I'm working on a site that has a financing simulator that asks for your data and a value related to cars, real estate and motorcycles. When simulating, it sends you to a page, calculating the closest result and sends your data to the database. However, he has a problem now. When you try to simulate, it no longer shows the result, it even loads the table but has no content, and the simulator form quickly pops up again. Check out an example at http://vitorconsorcios.com.br/simulador.php, below has the source code of the site. I've tried everything, but this is my last solution. What could be the cause of this? <?php include("injection.php"); /* if (isset($_POST['valorcon']) */ $valorcon = (int) tira_virgula_para_ponto( $_POST['valorcon'] ); $plano=anti_injection($_POST["plano"]); $tipo=anti_injection($_POST["tipo"]); $nomecon=anti_injection($_POST["nomecon"]); $telefone=anti_injection($_POST["telefone"]); $emailcon=anti_injection($_POST["emailcon"]); $cidadecon=anti_injection($_POST["cidadecon"]); if ($valorcon>0) { // Inseri a procura $tsql = " insert simulacao set plano='$plano' , tipo = '$tipo' , valor = $valorcon , nome = '$nomecon' , telefone = '$telefone' , email = '$emailcon' , cidade = '$cidadecon' "; //echo $tsql; //exit; $sql_insert = fbd($tsql,"","inserir simulacao"); ?> <div class="col-md-5"> <img src="img/simule.jpg" class="imagem" alt="Vitor Consórcios"> </div> <div class="col-md-7"> <h4>Confira a simualçao abaixo:</h4><br/> <table> <thead> <tr> <th>Descrição</th> <th>Valor do Crédito</th> <th>Valor da Parcela</th> <th>Valor da Meia Parcela</th> <th>Duração</th> </tr> </thead> <tbody> <?php $_SESSION['splano'] = $plano; $_SESSION['svalorcon'] = $valorcon; $_SESSION['stipo'] = $tipo ; if ($plano=='Crédito') { $tsql = " (SELECT * FROM `consulta` where tipo='$tipo' and credito>=$valorcon order by credito limit 2 ) UNION (SELECT * FROM `consulta` where tipo='$tipo' and credito<$valorcon order by credito desc limit 2 ) order by credito "; } ELSE { $tsql = " (SELECT * FROM `consulta` where tipo='$tipo' and parcela>=$valorcon order by parcela limit 2 ) UNION (SELECT * FROM `consulta` where tipo='$tipo' and parcela<$valorcon order by parcela desc limit 2 ) order by parcela "; } $_SESSION['sqlExecutar'] = $tsql ; //echo $tsql; //exit; $sql = fbd($tsql,"","Seleciona as empresa"); $num_rows = mysql_num_rows($sql); if ($num_rows>0) { ?> <script language= "JavaScript"> location.href="resultado.php" </script> <?php } ?> <script language= "JavaScript"> location.href="simulador.php" </script> <?php while($dados= mysql_fetch_array($sql)){ ?> <tr> <td align="left"><? echo $dados[descricao]; ?></td> <td>R$ <? echo valor_ponto_virgula( $dados["credito"] ); ?></td> <td>R$ <? echo valor_ponto_virgula( $dados["parcela"] ); ?></td> <td>R$ <? echo valor_ponto_virgula( $dados["parcela"]/2 ); ?></td> <td><? echo $dados["duracao"] ; ?></td> <?php } ?> </tbody> </table> </div> </div> <p> </p> <p> </p> </div> <?php } ELSE { ?> <h2>SIMULE AGORA SEU CONSÓRCIO!</h2><br/><br/> <div class="col-md-6"> <img src="img/simule.jpg" class="imagem" alt="Vitor Consórcios"> </div> <div class="col-md-1"></div> <form action="simulador.php" method="post" name="dados" id="dados" onSubmit="return validaform()"> <div class="col-md-5 esquerda"> Selecione o bem<br/> <select name="tipo" type="text" class="contat3" placeholder="Selecione o bem"> <option value="Imóvel"" style="background-color: #fff;">Imóveis</option> <option value="Automóvel"" style="background-color: #fff;">Automóveis</option> <option value="Moto" style="background-color: #fff;">Motos</option> </select><br/> Selecione o plano<br/> <select name="plano" type="text" class="contat3"> <option value="Crédito"" style="background-color: #fff;">Crédito</option> <option value="Parcela"" style="background-color: #fff;">Parcela</option> </select><br/> <input name="valorcon" type="text" id="valorcon" class="contat3" placeholder="Digite o valor" maxlength="1000" /><br/> <input name="nomecon" type="text" id="nomecon" class="contat3" placeholder="Nome" maxlength="1000" /><br/> <input name="telefone" type="text" onkeypress="Mascara('TEL',this,event);" type="text" id="telefone" class="contat3" placeholder="Telefone" /> <!--- <input name="tel2" type="text" id="tel2" onkeypress="Mascara('TEL',this,event);" /><br/> ---> <input name="emailcon" type="text" id="emailcon" class="contat3" placeholder="E-mal" maxlength="1000" /><br/> <input name="cidadecon" type="text" id="cidadecon" class="contat3" placeholder="Cidade" maxlength="1000" /> <br/><br/><br/> <a id="enviar-form" class="button solid-color" href="#">Enviar</a> <input type="submit" id="enviar-form-btn" style="display: none;" /> </div> </form> </div> <p> </p> <p> </p> </div> <?php } // 14-05-2018 ?> </div> </div>
Hi, I have a form with a submit button (Delete button). after I click the button I do few changes in database. Problem is that in this form, after the submit made, it still shows me old data that deleted.... So, I guess I need somehow to make a page refresh through a GET method. How do I do this? Thank u! So I made a template class, it's very simple, pretty much allows the usage like so: $template = new template("blogpost"); $template->fillBraces(array( "TITLE" => "How to bathe your chimpanzee", "AUTHOR" => "Jim Bo James" )); $template->render(); Simple, uses tpl files, similar to what phpbb used a long time back, not sure if they still do. My main goal for this is to have a file that has something like this: {HEADER} {MAIN_CONTENT} {FOOTER} and the above usage to stay the same, however that would fill the main_content part, and the header and footer would be grabbed from header/footer tpl files. Any idea on suggestions? The full class is posted below. class template { protected $_viewContents; function __construct($viewName) { $this->_viewContents = file_get_contents(TEMPLATE.$viewName.TEMPLATE_EXT); return; } function sourceOf($fileName) { return @file_get_contents(TEMPLATE.$fileName.TEMPLATE_EXT); } function fillLayout() { } function fillBraces($information, $replacement=NULL) { if (is_array($information)) { foreach ($information as $key => $val) { $this->_viewContents = str_ireplace("{".$key."}", $val, $this->_viewContents); } return; } elseif ($replacement!=NULL) { $this->_viewContents = str_ireplace("{".$information."}", $replacement, $this->_viewContents); return; } } function render() { echo $this->_viewContents; } } Thanks! I have made a shopping cart where I can add items from my sql table. But I dont know how to send the table to my email. this is my cart.php Can someone give me some tips? Thanks in advance. you can also check it out on http://fhcs.be/cart-demo3/ <?php // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); // Start the session session_start(); // Process actions $cart = $_SESSION['cart']; $action = $_GET['action']; switch ($action) { case 'add': if ($cart) { $cart .= ','.$_GET['id']; } else { $cart = $_GET['id']; } break; case 'delete': if ($cart) { $items = explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($_GET['id'] != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } $cart = $newcart; } break; case 'update': if ($cart) { $newcart = ''; foreach ($_POST as $key=>$value) { if (stristr($key,'qty')) { $id = str_replace('qty','',$key); $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($id != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } for ($i=1;$i<=$value;$i++) { if ($newcart != '') { $newcart .= ','.$id; } else { $newcart = $id; } } } } } $cart = $newcart; break; } $_SESSION['cart'] = $cart; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo &#0183; Cart</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="contents"> <h1>Please check quantities...</h1> <?php echo showCart(); ?> <p><a href="index.php">Back to bookshop...</a></p> </div> </body> </html> I have a list names in a database table in MySQL that I need to repeat the same search for on my system to get the associated information. Is there a Loop command or some type of trick to making a php script search table1.row1 then table1.row2 then table1.row3 etc. Basically using the row in the table as a variable for the other commands in the code. I really need some direction. Thanks. Hello, I need help with php, I don't understand what that could be , otherwise I run the page via a wampserver, I would be grateful for any kind of help. Hi I made a new design for my website and I made some changes. I want to use layout for my second site.
I'll like to know if my site is easier to browse through now and if you like the design better?. I test my site on internet explorer, chrome, and firefox. It is best to use site on better browsers like firefox and chrome to get a better experience of site. Thanks.
http://adjade.com
I have the following code in html: <html> <head> <script type="text/javascript"> <!-- function delayer(){ window.location = "http://VARIABLEVALUE.mysite.com" } //--> </script> <title>Redirecting ...</title> </head> <body onLoad="setTimeout('delayer()', 1000)"> <script type="text/javascript"> var sc_project=71304545; var sc_invisible=1; var sc_security="9c433fretre"; </script> <script type="text/javascript" src="http://www.statcounter.com/counter/counter.js"></script><noscript> <div class="statcounter"><a title="vBulletin statistics" href="http://statcounter.com/vbulletin/" target="_blank"><img class="statcounter" src="http://c.statcounter.com/71304545/0/9c433fretre/1/" alt="vBulletin statistics" ></a></div></noscript> </body> </html> Is a basic html webpage with a timer redirect script and a stascounter code. I know a bit about html and javascript, but almost nothing about php. My question is: How a can convert this html code into a php file, in order to send a variable value using GET Method and display this variable value inside the javascript code where says VARIABLEVALUE. Thanks in adavance for your help. Hi, I have some code which displays my blog post in a foreach loop, and I want to add some social sharing code(FB like button, share on Twitter etc.), but the problem is the way I have my code now, creates 3 instances of the sharing buttons, but if you like one post, all three are liked and any thing you do affects all of the blog post. How can I fix this? <?php include ("includes/includes.php"); $blogPosts = GetBlogPosts(); foreach ($blogPosts as $post) { echo "<div class='post'>"; echo "<h2>" . $post->title . "</h2>"; echo "<p class='postnote'>" . $post->post . "</p"; echo "<span class='footer'>Posted By: " . $post->author . "</span>"; echo "<span class='footer'>Posted On: " . $post->datePosted . "</span>"; echo "<span class='footer'>Tags: " . $post->tags . "</span>"; echo ' <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> <a class="addthis_button_tweet"></a> <a class="addthis_counter addthis_pill_style"></a> </div> <script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=webguync"></script>'; echo "</div>"; } ?> Hi, I need to insert some code into my current form code which will check to see if a username exist and if so will display an echo message. If it does not exist will post the form (assuming everything else is filled in correctly). I have tried some code in a few places but it doesn't work correctly as I get the username message exist no matter what. I think I am inserting the code into the wrong area, so need assistance as to how to incorporate the username check code. $sql="select * from Profile where username = '$username'; $result = mysql_query( $sql, $conn ) or die( "ERR: SQL 1" ); if(mysql_num_rows($result)!=0) { process form } else { echo "That username already exist!"; } the current code of the form <?PHP //session_start(); require_once "formvalidator.php"; $show_form=true; if (!isset($_POST['Submit'])) { $human_number1 = rand(1, 12); $human_number2 = rand(1, 38); $human_answer = $human_number1 + $human_number2; $_SESSION['check_answer'] = $human_answer; } if(isset($_POST['Submit'])) { if (!isset($_SESSION['check_answer'])) { echo "<p>Error: Answer session not set</p>"; } if($_POST['math'] != $_SESSION['check_answer']) { echo "<p>You did not pass the human check.</p>"; exit(); } $validator = new FormValidator(); $validator->addValidation("FirstName","req","Please fill in FirstName"); $validator->addValidation("LastName","req","Please fill in LastName"); $validator->addValidation("UserName","req","Please fill in UserName"); $validator->addValidation("Password","req","Please fill in a Password"); $validator->addValidation("Password2","req","Please re-enter your password"); $validator->addValidation("Password2","eqelmnt=Password","Your passwords do not match!"); $validator->addValidation("email","email","The input for Email should be a valid email value"); $validator->addValidation("email","req","Please fill in Email"); $validator->addValidation("Zip","req","Please fill in your Zip Code"); $validator->addValidation("Security","req","Please fill in your Security Question"); $validator->addValidation("Security2","req","Please fill in your Security Answer"); if($validator->ValidateForm()) { $con = mysql_connect("localhost","uname","pw") or die('Could not connect: ' . mysql_error()); mysql_select_db("beatthis_beatthis") or die(mysql_error()); $FirstName=mysql_real_escape_string($_POST['FirstName']); //This value has to be the same as in the HTML form file $LastName=mysql_real_escape_string($_POST['LastName']); //This value has to be the same as in the HTML form file $UserName=mysql_real_escape_string($_POST['UserName']); //This value has to be the same as in the HTML form file $Password= md5($_POST['Password']); //This value has to be the same as in the HTML form file $Password2= md5($_POST['Password2']); //This value has to be the same as in the HTML form file $email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file $Zip=mysql_real_escape_string($_POST['Zip']); //This value has to be the same as in the HTML form file $Birthday=mysql_real_escape_string($_POST['Birthday']); //This value has to be the same as in the HTML form file $Security=mysql_real_escape_string($_POST['Security']); //This value has to be the same as in the HTML form file $Security2=mysql_real_escape_string($_POST['Security2']); //This value has to be the same as in the HTML form file $sql="INSERT INTO Profile (`FirstName`,`LastName`,`Username`,`Password`,`Password2`,`email`,`Zip`,`Birthday`,`Security`,`Security2`) VALUES ('$FirstName','$LastName','$UserName','$Password','$Password2','$email','$Zip','$Birthday','$Security','$Security2')"; //echo $sql; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } else{ mail('email@gmail.com','A profile has been submitted!',$FirstName.' has submitted their profile',$body); echo "<h3>Your profile information has been submitted successfully.</h3>"; } mysql_close($con); $show_form=false; } else { echo "<h3 class='ErrorTitle'>Validation Errors:</h3>"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "<p class='errors'>$inpname : $inp_err</p>\n"; } } } if(true == $show_form) { ?> Advance thank you. Can you help please. The error..... Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given in C:\wamp\www\test_dabase.php on line 24 code. Code: [Select] <?php //database connection. $DB = mysql_connect("localhost","root") or die(mysql_error()); if($DB){ //database name. $DB_NAME="mysql"; //select database and name. $CON=mysql_select_db($DB_NAME,$DB)or die(mysql_error()."\nPlease change database name"); // if connection. }if($CON){ //show tables. $mysql_show="SHOW TABLES"; //select show and show. $mysql_select2="mysql_query(".$mysql_show.") or die(mysql_error())"; } //if allowed to show. if($mysql_select2){ //while it and while($data=mysql_fetch_assoc($mysql_select2)){ //show it. echo $data; } } ?> hey gurus, i am a newbie php coder.. i am learning by example. what i am trying to do is write a piece of code which will alter 3 tables (user, bonus_credit, bonus_credit_usage) ---------------------------------------------------------------- the table structure that will be used is as follows: user.bonus_credit user.ID bonus_credit.bonusCode bonus_credit.qty bonus_credit.value bonus_credit_usage.bonusCode bonus_credit_usage.usedBy ---------------------------------------------------------------- so lets say, in bonus_credit i have the following bonusCode = 'facebook' (this is the code they have to type to redeem the bonus qty = '10' ( number of times the bonusCode can be redeemed, but same person can't redeem it more than once) value = '5' (this is the amount of bonus_credit for each qty) Now, I need to write a code that check to see if the code has been redeemed in the bonus_credit_usage table and if the user.ID exists in this table as bonus_code_usage.usedBy, then give an error that its already been used and if it hasn't been used, then subtract 1 from qty, add ID to usedBy and then add the value to the bonus_credit ----------------------- i have started the steps just to create a simple textbox and entering a numeric value to bonus_credit, and that works.. but now i have to use JOIN and IF and ELSE.. which is a little too advanced for me.. so i'd appreciate a guide as i write the code. if(isset($_REQUEST['btnBonus'])) { $bonus_credit = addslashes($_REQUEST['bonusCode']); $query = "update user set bonus_credit=bonus_credit+'".$bonus_credit."' where id='".$_SESSION['SESS_USERID']."'"; echo "<script>window.location='myreferrals.php?msgs=2';</script>"; mysql_query($query) or die(mysql_error()); } Can I combine also HTML code in PHP function? For example, can a PHP function include HTML form and the PHP code to handle this form? If yes, this will make my main code much more smaller and readable. If not, is there a way to define an "external macro" like, which allow me to replace pre-defined lines of code with short alias? |