PHP - Can This Query Be Made Simpler?
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 Similar Tutorials $array = array(); for ($i = 97; $i < 123; $i++) { $array[] = chr($i); } for ($i = 65; $i < 91; $i++) { $array[] = chr($i); } Its quite time consuming looping, perhaps combine in 1 or? Hi! 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 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. 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 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, Where can i find the source of the pre made php functions? Greets, Scuar. 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!
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>
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 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. 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> 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. Here is my code: // Start MySQL Query for Records $query = "SELECT codes_update_no_join_1b" . "SET orig_code_1 = new_code_1, orig_code_2 = new_code_2" . "WHERE concat(orig_code_1, orig_code_2) = concat(old_code_1, old_code_2)"; $results = mysql_query($query) or die(mysql_error()); // End MySQL Query for Records This query runs perfectly fine when run direct as SQL in phpMyAdmin, but throws this error when running in my script??? Why is this??? Code: [Select] 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 '= new_code_1, orig_code_2 = new_code_2WHERE concat(orig_code_1, orig_c' at line 1 Hello all,
Based on the suggestion of you wonderful folks here, I went away for a few days (to learn about PDO and Prepared Statements) in order to replace the MySQLi commands in my code. That's gone pretty well thus far...with me having learnt and successfully replaced most of my "bad" code with elegant, SQL-Injection-proof code (or so I hope).
The one-and-only problem I'm having (for now at least) is that I'm having trouble understanding how to execute an UPDATE query within the resultset of a SELECT query (using PDO and prepared statements, of course).
Let me explain (my scenario), and since a picture speaks a thousand words I've also inlcuded a screenshot to show you guys my setup:
In my table I have two columns (which are essentially flags i.e. Y/N), one for "items alreay purchased" and the other for "items to be purchased later". The first flag, if/when set ON (Y) will highlight row(s) in red...and the second flag will highlight row(s) in blue (when set ON).
I initially had four buttons, two each for setting the flags/columns to "Y", and another two to reverse the columns/flags to "N". That was when I had my delete functionality as a separate operation on a separate tab/list item, and that was fine.
Now that I've realized I can include both operations (update and delete) on just the one tab, I've also figured it would be better to pare down those four buttons (into just two), and set them up as a toggle feature i.e. if the value is currently "Y" then the button will set it to "N", and vice versa.
So, looking at my attached picture, if a person selects (using the checkboxes) the first four rows and clicks the first button (labeled "Toggle selected items as Purchased/Not Purchased") then the following must happen:
1. The purchased_flag for rows # 2 and 4 must be switched OFF (set to N)...so they will no longer be highlighted in red.
2. The purchased_flag for row # 3 must be switched ON (set to Y)...so that row will now be highlighted in red.
3. Nothing must be done to rows # 1 and 5 since: a) row 5 was not selected/checked to begin with, and b) row # 1 has its purchase_later_flag set ON (to Y), so it must be skipped over.
Looking at my code below, I'm guessing (and here's where I need the help) that there's something wrong in the code within the section that says "/*** loop through the results/collection of checked items ***/". I've probably made it more complex than it should be, and that's due to the fact that I have no idea what I'm doing (or rather, how I should be doing it), and this has driven me insane for the last 2 days...which prompted me to "throw in the towel" and seek the help of you very helpful and intellegent folks. BTW, I am a newbie at this, so if I could be provided the exact code, that would be most wonderful, and much highly appreciated.
Thanks to you folks, I'm feeling real good (with a great sense of achievement) after having come here and got the great advice to learn PDO and prepared statements.
Just this one nasty little hurdle is stopping me from getting to "end-of-job" on my very first WebApp. BTW, sorry about the long post...this is the best/only way I could clearly explaing my situation.
Cheers guys!
case "update-delete": if(isset($_POST['highlight-purchased'])) { // ****** Setup customized query to obtain only items that are checked ****** $sql = "SELECT * FROM shoplist WHERE"; for($i=0; $i < count($_POST['checkboxes']); $i++) { $sql=$sql . " idnumber=" . $_POST['checkboxes'][$i] . " or"; } $sql= rtrim($sql, "or"); $statement = $conn->prepare($sql); $statement->execute(); // *** fetch results for all checked items (1st query) *** // $result = $statement->fetchAll(); $statement->closeCursor(); // Setup query that will change the purchased flag to "N", if it's currently set to "Y" $sqlSetToN = "UPDATE shoplist SET purchased = 'N' WHERE purchased = 'Y'"; // Setup query that will change the purchased flag to "Y", if it's currently set to "N", "", or NULL $sqlSetToY = "UPDATE shoplist SET purchased = 'Y' WHERE purchased = 'N' OR purchased = '' OR purchased IS NULL"; $statementSetToN = $conn->prepare($sqlSetToN); $statementSetToY = $conn->prepare($sqlSetToY); /*** loop through the results/collection of checked items ***/ foreach($result as $row) { if ($row["purchased"] != "Y") { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToY = $statementSetToY->fetch(); foreach($resultSetToY as $row) { $statementSetToY->execute(); } } else { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToN = $statementSetToN->fetch(); foreach($resultSetToN as $row) { $statementSetToN->execute(); } } } break; }CRUD Queston.png 20.68KB 0 downloads If you also have any feedback on my code, please do tell me. I wish to improve my coding base. Basically when you fill out the register form, it will check for data, then execute the insert query. But for some reason, the query will NOT insert into the database. In the following code below, I left out the field ID. Doesn't work with it anyways, and I'm not sure it makes a difference. Code: Code: [Select] mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); Full code: Code: [Select] <?php include_once("includes/config.php"); ?> <!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"> <head> <title><? $title; ?></title> <meta http-equiv="Content-Language" content="English" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> </head> <body> <div id="wrap"> <div id="header"> <h1><? $title; ?></h1> <h2><? $description; ?></h2> </div> <? include_once("includes/navigation.php"); ?> <div id="content"> <div id="right"> <h2>Create</h2> <div id="artlicles"> <?php if(!$_SESSION['user']) { $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $name = mysql_real_escape_string($_POST['name']); $server_type = mysql_real_escape_string($_POST['type']); $description = mysql_real_escape_string($_POST['description']); if(!$username || !$password || !$server_type || !$description || !$name) { echo "Note: Descriptions allow HTML. Any abuse of this will result in an IP and account ban. No warnings!<br/>All forms are required to be filled out.<br><form action='create.php' method='POST'><table><tr><td>Username</td><td><input type='text' name='username'></td></tr><tr><td>Password</td><td><input type='password' name='password'></td></tr>"; echo "<tr><td>Sever Name</td><td><input type='text' name='name' maxlength='35'></td></tr><tr><td>Type of Server</td><td><select name='type'> <option value='Any'>Any</option> <option value='PvP'>PvP</option> <option value='Creative'>Creative</option> <option value='Survival'>Survival</option> <option value='Roleplay'>RolePlay</option> </select></td></tr> <tr><td>Description</td><td><textarea maxlength='1500' rows='18' cols='40' name='description'></textarea></td></tr>"; echo "<tr><td>Submit</td><td><input type='submit'></td></tr></table></form>"; } elseif(strlen($password) < 8) { echo "Password needs to be higher than 8 characters!"; } elseif(strlen($username) > 13) { echo "Username can't be greater than 13 characters!"; } else { $check1 = mysql_query("SELECT username,name FROM servers WHERE username = '$username' OR name = '$name' LIMIT 1"); if(mysql_num_rows($check1) < 0) { echo "Sorry, there is already an account with this username and/or server name!"; } else { $ip = $_SERVER['REMOTE_ADDR']; mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); echo "Server has been succesfully created!"; } } } else { echo "You are currently logged in!"; } ?> </div> </div> <div style="clear: both;"> </div> </div> <div id="footer"> <a href="http://www.templatesold.com/" target="_blank">Website Templates</a> by <a href="http://www.free-css-templates.com/" target="_blank">Free CSS Templates</a> - Site Copyright MCTop </div> </div> </body> </html> I was just wondering if it's possible to run a query on data that has been returned from a previous query? For example, if I do Code: [Select] $sql = 'My query'; $rs = mysql_query($sql, $mysql_conn); Is it then possible to run a second query on this data such as Code: [Select] $sql = 'My query'; $secondrs = mysql_query($sql, $rs, $mysql_conn); Thanks for any help Say I have this query: site.com?var=1 ..I have a form with 'var2' field which submits via get. Is there a way to produce: site.com?var=1&var2=formdata I was hoping there would be a quick way to affix, but can't find any info. Also, the query could sometimes be: site.com?var2=formdata&var=1 I would have to produce: site.com?var2=updatedformdata&var=1 Is my only option to further parse the query? I'm trying to update every record where one field in a row is less than the other. The code gets each row i'm looking for and sets up the query right, I hope I combined the entire query into one string each query seperated by a ; so it's like UPDATE `table` SET field2= '1' WHERE field1= '1';UPDATE `table` SET field2= '1' WHERE field1= '2';UPDATE `table` SET field2= '1' WHERE field1= '3';UPDATE `table` SET field2= '1' WHERE field1= '4';UPDATE `table` SET field2= '1' WHERE field1= '5'; this executes properly if i run the query in phpMyAdmin, however when I run the query in PHP, it does nothing... Any advice? |