-
Posts
24,566 -
Joined
-
Last visited
-
Days Won
822
Everything posted by Barand
-
Show me how to load those data images into a test database so I can check out the subqueries and I'll be glad to help.
-
try <?php require 'db_inc.php'; $db = pdoConnect(); // function defined in db_inc.php $search = $_GET['search'] ?? ''; $tdata = ''; $stmt = $db->prepare("SELECT ID , GAME , PLATFORM , Owned FROM games WHERE GAME LIKE ? "); $stmt->execute([ "$search%" ]); foreach ($stmt as $row) { $tdata .= "<tr><td>" . join('</td><td>', $row) . "</td></tr>\n"; } ?> <!DOCTYPE html> <html> <head> <title>Sample Search</title> <style type='text/css'> body { font-family: calibri, sans-serif; font-size: 11pt;} header{ background-color: black; color: white; padding: 16px; } form { padding: 16px; } table { width: 75%; margin: 30px auto; border-collapse: collapse; } th { background-color: black; color: white; padding: 8px; } td { padding: 4px 8px;} </style> </head> <body> <header> <h1>Sample</h1> </header> <form method='GET'> Search for: <input type="text" name="search" value="<?=$search?>" size="40"> <input type="submit" name="btnSub" value="Search"> </form> <div> <?php if ($search) { ?> <table border='1'> <thead> <tr> <th>ID</th> <th>GAME</th> <th>PLATFORM</th> <th>OWNED</th> </tr> </thead> <tbody> <?=$tdata?> </tbody> </table> <?php } ?> </div> </body> </html>
-
loop through array with incremental for striped table
Barand replied to Wal-Wal-2's topic in PHP Coding Help
Try incrementing the counter at the end of the loop. Also no need for all the duplicate code. All you need is to set a variable $suc = $counter % 2 == 1 ? 'success' : ''; E.G. $counter = 0; foreach ($res as $row) { $suc = $counter % 2 == 1 ? 'success' : ''; $tdata .= "<tr class='$suc'> <td>{$row['firstname']}</td> <td>{$row['lastname']}</td> </tr>"; $counter++; } then <table> <?=$tdata?> </table> -
The more information a query retrieves the slower it will run. In the code below all you want is a single count yet you retrieve every column in every record. // find number of rows in the db $query = "SELECT * FROM menu_update WHERE special_of_theday = 1 AND restaurant_type = '".$selected_restaurant_type."' "; $query_result = mysqli_query($connection, $query); $row_count = mysqli_fetch_array($query_result); $total_rows = mysqli_num_rows($query_result); Far more efficient to $query = "SELECT COUNT(*) as total FROM menu_update WHERE special_of_theday = 1 AND restaurant_type = '$selected_restaurant_type' "; $query_result = mysqli_query($connection, $query); $row = mysqli_fetch_array($query_result); $total_rows = $row['total'];
-
It would appear from the code that you would always have links 1 2 3 4 ... N except when you are on the last page. You show the links on this condition... if ($page_number != $expected_number_of_pages) Do you, perchance, only have two pages at present? And do you mean $page_number or do you mean $current_page (confusing names)
-
Your misleading choice of variables names no doubt contributed to the problem. There are other things could be improved too Use prepared queries instead of putting variables directly into the sql query strings. (I would also recommend PDO in preference to mysqli) use css classes instead of repetitive inline style definitions you are using deprecated html markup code (eg <tr bgcolor = "#cccccc">) you use a lot of unnecessary concatenation when building strings - a common source of errors.
-
In your pagination loop you set all the links to the same page number! Should be $data = array( 'page' => $current_page, <-- CHANGED 'country' => $cleaned_current_page_country );
-
Do not use $_REQUEST. Use either $_POST or $_GET depending on your form's method attribute. (In this case, as you are updating the cart data, it should be POST.) session_start(); $cart_items = $_SESSION["cart_items"] ?? []; $id = $_POST["element_id"] ?? 0; $quantity = $_POST["quantity"] ?? 0; if ($id && $quantity) { if (!isset($cart_items[$id])) { $cart_items[$id] = 0; } $cart_items[$id] += $quantity; } var_dump($cart_items);
-
I have just noticed you don't use the $page_url in those pagination links. It looks like you intended to but then just used the query string $the_query = http_build_query($data); $page_url .= '?' . $the_query; echo '<li><a href=" '.$the_query.' ">'.$current_page.'</a></li> '; As you go to the same page that should be sufficient but I think you will need the preceding "?" Try $the_query = http_build_query($data); $the_query = '?' . $the_query; echo "<li><a href=\"$the_query\">$current_page</a></li>";
-
What does $page_url contain? Try var_dump($page_url) on line 7 after you set its value;
-
does it work if you put the "Italian.php" back in the middle of that url?
-
Have you checked the content of $data[0]? If it is blank, your query becomes "SELECT * FROM games WHERE id = ", and that would give you that syntax error. edit: P.S. You should be using a prepared statement when dealing with POST data
-
PHP mail function how to set sender mail id based on if condition?
Barand replied to aveeva's topic in PHP Coding Help
One more attempt. Here's a script which puts the hints I gave you into practice. As you can see, it splits the ordered items into separate order depending on the SKU group SAMPLE: Code (read, understand what's going on and learn. Refer to php.net manual if you don't know what something does.) (Not an elseif()..elseif() to be found!) <?php const HOST = 'localhost'; # const USERNAME = '????'; # const PASSWORD = '????'; # const DATABASE = '????'; # These lines would # function pdoConnect($dbname=DATABASE) # normally be in { # $db = new PDO("mysql:host=".HOST.";dbname=$dbname;charset=utf8",USERNAME,PASSWORD); # an included file $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); # $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); # $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); # return $db; # } # $pdo = pdoConnect(); // // CREATE TEST DATA USED BY THIS EXAMPLE // $pdo->exec("CREATE TABLE IF NOT EXISTS aveeva ( id int not null auto_increment primary key, order_no int, sku int, product varchar(50), qty int ) "); $pdo->exec("REPLACE INTO aveeva (id, order_no, sku, product, qty) VALUES (1,1020345, 12345, 'Pair of left-footed socks', 2), (2,1020345, 35547, 'Square Hula hoop', 1), (3,1020345, 12346, 'Pair of right-footed socks', 2), (4,1020345, 62347, 'Pair of three-legged tights', 5), (5,1020345, 45501, 'String vest', 1), (6,1020345, 45501, 'Thermal long johns (red)', 2), (7,1020345, 22105, 'Staffordshire pot dog', 2), (8,1020345, 38962, '250 Kg dumbell set', 1), (9,1020345, 23176, 'Ming vase', 1), (10,1020345, 23194, 'Porcelain elephant', 1), (11,1020345, 38547, '0.5 metre yoga mat', 1) "); // DUMMY CLASS TO PROVIDE THE METHODS YOU USED class Magee { private $fromName; private $body; private $subject; private $type; private $sendTo; public function __construct() { } public function setFromName($str) { $this->fromName = $str; } public function setBody($str) { $this->body = $str; } public function setSubject($str) { $this->subject = $str; } public function setType($str) { $this->type = $str; } public function setToEmail($str) { $this->sendTo = $str; } public function send() { // // Instead of sending emails // we just build content // for demonstration output // $out = "<fieldset><legend>TO: {$this->sendTo}</legend> <label>From</label>{$this->fromName}<br> <label>Subject</label>{$this->subject}<br> {$this->body}<br> "; $out .= "</fieldset>"; return $out; } } #Magee // define email addresses for the sku groups const DEFAULT_ADDY = '[email protected]'; $addys = [ 2 => '[email protected]', 3 => '[email protected]', 4 => '[email protected]' ]; $res = $pdo->query("SELECT sku , product , qty , order_no FROM aveeva ORDER BY order_no, sku "); $orders = []; // // Split the items for each order // into groups depending the first // digit of their SKU // foreach ($res as $r) { $ono = array_pop($r); $sku1 = substr($r['sku'], 0, 1); if (!isset($addys[$sku1])) { $sku1 = 0; } $orders[$ono][$sku1][] = $r; } // // Build the email bodies from the array data // $emailsSent = ''; foreach ($orders as $ono => $odata) { foreach ($odata as $sku1 => $sdata) { $message = "<table border='1'> <caption>Order No: $ono</caption> <tr><th>SKU</th><th>Product</th><th>Quantity</th></tr>\n"; foreach ($sdata as $item) { $message .= "<tr><td>" . join("</td><td>", $item) . "</td></tr>\n"; } $message .= "</table>\n"; $emailsSent .= sendMailbasedOnSku($message, $addys, $sku1); } } function sendMailbasedOnSku($message, $addys, $sku1) { $emailTemplate = new Magee; $emailTemplate->setFromName('GIRI Test mail'); $emailTemplate->setBody($message); $emailTemplate->setSubject("Custom Email from observer"); $emailTemplate->setType('html'); // GET THE APPROPRIATE EMAIL ADDRESS $sendTo = $addys[$sku1] ?? DEFAULT_ADDY; // USE IT $emailTemplate->setToEmail($sendTo); return $emailTemplate->send(); } ?> <html> <head> <title>Example</title> <style type='text/css'> body { font-family: clibri, sans-serif; font-size: 11pt;} fieldset { width: 70%; margin: 16px auto; padding: 16px;} legend { background-color: black; color: white; padding: 4px;} label { display: inline-block; width: 120px; font-weight: 600;} table { width: 50%; margin: 16px auto; border-collapse: collapse;} th { background-color: black; color: white; padding: 8px;} td { padding: 4px 8px;} </style> </head> <body> <?=$emailsSent?> </body> </html> -
PHP mail function how to set sender mail id based on if condition?
Barand replied to aveeva's topic in PHP Coding Help
Your problems are mainly because you are trying to write code before you have learnt to read. In my first post I said you needed 2 things. The first you have totally disregarded despite my spoonfeeding you the required code. The second addresses the problem you are now having and has also been ignored. Good luck and goodbye. -
Did you mean something like this? /** * write query results to text table * * @param PDO $pdo * @param mixed $sql * @param mixed $params * @return query results */ function pdo2text(PDO $pdo, $sql, $params=[]) { $res = $pdo->prepare($sql); $res->execute($params); $data = $res->fetchAll(PDO::FETCH_ASSOC); if (count($data) == 0) { return "NO RECORDS FOUND"; } $out = "<pre>\n"; $heads = array_keys($data[0]); $widths = []; foreach ($heads as $h) { $widths[] = strlen($h); } foreach ($data as $row) { foreach (array_values($row) as $c => $v) { $widths[$c] = max($widths[$c], strlen($v)); } } $horiz = '+'; $format = '|'; foreach ($widths as $w) { $horiz .= str_repeat('-', $w+2) . '+'; $format .= " %-{$w}s |"; } $format .= "\n"; $out .= "$horiz\n"; $out .= vsprintf($format, $heads); $out .= "$horiz\n"; foreach ($data as $row) { $out .= vsprintf($format, $row); } $out .= $horiz; return $out . '</pre>'; } echo pdo2text($pdo, "SELECT * FROM ssm.user");
-
How to create a set of data from string to insert in MySQL
Barand replied to FrancescoITA's topic in PHP Coding Help
Use DateInterval and DatePeriod classes EG <?php function listDates($data06, $data03) { switch ($data06) { case 'annual': $interval = 'P1Y'; $num = 4; break; case 'half year': $interval = 'P6M'; $num = 9; } $dates = new DatePeriod(new DateTime($data03), new DateInterval($interval), $num); $k = 0; foreach ($dates as $d) { printf("\n%2d) %s", ++$k, $d->format('Y-m-d') ); } } ?> <html> <head> <title>Example</title> </head> <body> <pre> <?= listDates('annual', '2019-01-01') ?> <br> <?= listDates('half year', '2019-01-01') ?> </pre> </body> </html> Results 1) 2019-01-01 2) 2020-01-01 3) 2021-01-01 4) 2022-01-01 5) 2023-01-01 1) 2019-01-01 2) 2019-07-01 3) 2020-01-01 4) 2020-07-01 5) 2021-01-01 6) 2021-07-01 7) 2022-01-01 8) 2022-07-01 9) 2023-01-01 10) 2023-07-01 -
I have a similar one which I use to test queries when I can't be bothered to fire up Workbench. It has some differences to yours I don't like functions that connect to the db, I prefer to pass the connection It works for any select query, not hardwired to DESCRIBE (although it will work with that) Uses prepared queries/parameters function pdo2html(PDO $pdo, $sql, $params=[]) { $res = $pdo->prepare($sql); $res->execute($params); $data = $res->fetch(); if ($data) { $out = "<table border='1'>\n"; $heads = array_keys($data); $out .= "<tr><th>".join('</th><th>', $heads)."</th></tr>\n"; do { $out .= "<tr><td>".join('</td><td>', $data)."</td></tr>\n"; } while ($data = $res->fetch()); $out .= "</table>\n"; } else { $out = "NO RECORDS FOUND"; } return $out; } Usage <?php include 'db_inc.php'; $pdo = pdoConnect('humbug'); $role = 2; ?> <html> <head> <style type='text/css'> table { border-collapse: collapse; font-family: sans-serif;} th { background-color: #000; color: #FFF; padding: 8px; } td { padding: 4px 8px; } </style> </head> <body> <?= pdo2html($pdo, "DESCRIBE ssm_user")?> <br> <?= pdo2html($pdo, "SELECT * FROM ssm_user WHERE role_id = ?", [$role] )?> </body> </html> Result
-
Need help on getting products to insert into database
Barand replied to purge08's topic in PHP Coding Help
That is what I thought. The parent category is a property of the subcategory, not of the product. If you know the subcategory you can derive the parent category. You don't need both. Similarly, vendor status is a property of the vendor, not the product. Column names like "product_features" and "product_keywords" implies there may be delimited lists in those columns that should be in separate tables. Ditto the image columns - separate table with a record for each image. -
-
Do I take it that this is from Workbench? Have you checked host, user, password, port settings? (You do your development on a remote host!?)
-
Have you not mastered copy and paste yet? // database connection config $dbHost = 'localhost'; $dbUser = ''; $dbPass = ''; $dbName = ''; mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT); // <-- ADD IT HERE !!! $dbConn = mysqli_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error()); mysqli_select_db($dbConn,$dbName) or die('Cannot select database. ' . mysqli_error()); function dbQuery($sql) { $result = mysqli_query($dbConn,$sql) or die(mysql_error()); return $result; }
-
Get a copy of MySQL Workbench. There's a right-click menu option to go straight to it.
-
Easiest way is to add this line to your included connection.php mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT); immediately before the line that connects to the database (either with mysqli_connect() or new mysqli() )
-
You still haven't ensured that error is always defined $error = ''; // <----------- YOU MISSED HIS LINE TO DEFINE $error if($check) { header('location:success_package'); exit; } else { $error = '<div class="alert-warning" style="height:60px;"> <p style="line-height:40px;">Error in posting</p> </div>'; }
-
The wrong colours in the code was caused by apostrophe in the text preceding the code. I have moved the text out and code looks pretty now.