Jump to content

Barand

Moderators
  • Posts

    24,551
  • Joined

  • Last visited

  • Days Won

    821

Community Answers

  1. Barand's post in select statements and html tables was marked as the answer   
    That last post shows two sets of output. Your code, from what I can decipher from the poorly formatted mess (use code tags), shows three queries and output sets.
     
    Having output one table you cannot then append a column to those rows - they've already been output. You need to have the data available before you output.
     
    If you use multiple queries you have to store the data in an array then output from the array.
     
    Personally, I would prefer to use a single query if I can.
  2. Barand's post in Getting the input field of only one item was marked as the answer   
    Create an array for the quantity inputs using the id as the key.
     

    <input name="quantity[$f->id]" type="number" >You can then access individual input 

    $quantity = $_POST['quantity'][$id]
  3. Barand's post in mysqli_fetch_assoc returns only 1 result was marked as the answer   
    How about trying:
     
    SELECT uid, password FROM ....
  4. Barand's post in display user even if select query returns nothing was marked as the answer   
    SELECT
    u.name
    , u.surname
    , u.id
    , count(f.date_made) as date_made
    FROM
    users u
    LEFT JOIN
    firsts f
    ON u.id = f.usr_id
        AND DATE(`f.date_made`) BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE()
    GROUP BY u.id ;
  5. Barand's post in How to escape Ajax Request in PHP was marked as the answer   
    Perhaps it doesn't echo because you commented out the line.
     
    Don't escape the variable, use prepared statements instead, binding the variable as a parameter.
     
    EDIT: BTW, PDO makes it a lot easier than mysqli
  6. Barand's post in add a second value to an associative array using substr($line, 91, 10); was marked as the answer   
    Does this pseudocode help?
     

    while not EOF if it is a line with 'AA' store the key and items in the array endif endwhileNow your array contains only the items you wanted so there is no need to filter them out. Sorry I can't be any clearer.
  7. Barand's post in Were default property values always allowed? was marked as the answer   
    Even back in PHP4 days (when they were defined with "var" instead of "public" etc) you could assign default literal values.
  8. Barand's post in Problem in inserting partial data from dropdown to mysql using PHP was marked as the answer   
    You are not creating the option values correctly.
     
    Currently you are creating

    <option value =Accounts Dept>What you should create is
    <option value="Accounts Dept">Without the quotes the value is terminated at the space after Accounts.
  9. Barand's post in Having trouble with Array value saying "null"? was marked as the answer   
    My guess would be that there is something wrong with the data,
     
    What is the table structure?
    Can you show us some sample data? For example, are you storing income values with currency symbols?
     
    Don't store ages. It constantly needs updating; store the date of birth instead
  10. Barand's post in Why $Phone is null ? was marked as the answer   
    It's your formatting and inconsistent indentation that is causing the confusion.
     
    As for your problem, you return the number from the function but throw it away. You need to assign the result of the function call to a variable EG

    $resultPhone = format_phone_number($phoneData);Functions that return values should not have side effects, such as echoing output.
  11. Barand's post in Join table and get only one row from other table was marked as the answer   
    SELECT
    u.name
    , MAX(DATE(ul.login_time)) as latest
    FROM USER_LOGINS ul
    INNER JOIN USERS u USING(userid)
    GROUP BY u.name
  12. Barand's post in I am having issue with selecting a certain id with this query. Need help. was marked as the answer   
    It OK to have AND and OR in a query but it is always better to use parentheses when doing so.
     
    EG Instead of
    ... WHERE A AND B OR C
     
    use
    ... WHERE A AND (B OR C)
     
    This removes any ambiguity about whether you meant (A AND B) OR C
  13. Barand's post in Multiple Tables Output in phpmyadmin was marked as the answer   
    Don't use "SELECT * ", specify the columns you need. Then apply aliases to differentiate between those with the same name.
     
    Use explicit join syntax. Example
    QUANTITY is used on stock_stockin_product and stock_product tables SELECT sip.quantity as quantity_sip , sp.quantity as quantity_sp , whatever_else FROM stock_stockin si INNER JOIN stock_stockin_product sip ON si.id=sip.stockin_id INNER JOIN stock_product sp ON sp.id=sip.product_id WHERE stock_date>='1488366000' AND stock_date<='1488538800' AND stock_product.brand_id='11' AND stock_product.category_id='27' AND stock_product.model LIKE '%iphone 6%' AND stock_stockin.branch LIKE '%henderson%' GROUP BY si.id
  14. Barand's post in Select name from a table! was marked as the answer   
    Your join syntax is wrong.
    SELECT cat_name FROM domeniu_activitate d INNER JOIN user_pers_juridica u ON d.cat_id = u.cat_id WHERE product_id = '$id' It is also better to use prepared queries. You should not be putting data ($id) directly into your queries.
  15. Barand's post in PDO Looping was marked as the answer   
    The times when you might want similar to that is when you want to specify the array indexes For example
    if ($stmt->execute()) { while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $products[ $row['user_id'] ] = $row; } } or to group results
    if ($stmt->execute()) { while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $products[ $row['cat_id'] ][] = $row; } }
  16. Barand's post in alter table add column ... like this other column over here? was marked as the answer   
    You can create a table which has exactly the same structure as another
    CREATE TABLE table2 LIKE table1; I know of nothing similar down at the ADD COLUMN level.
  17. Barand's post in edit row if hashtag field already exists with the varible was marked as the answer   
    Put unique key on hashtag column.
    CREATE TABLE `hashtag` ( `hashtag_id` int(11) NOT NULL AUTO_INCREMENT, `hashtag` varchar(45) DEFAULT NULL, `link` varchar(45) DEFAULT NULL, PRIMARY KEY (`hashtag_id`), UNIQUE KEY `idx_hashtag_hashtag` (`hashtag`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; mysql> insert into hashtag (hashtag, link) VALUES     -> ('abc', 'xyz'),     -> ('bcd', 'stu'); Query OK, 2 rows affected (0.05 sec) mysql> select * from hashtag; +------------+---------+------+ | hashtag_id | hashtag | link | +------------+---------+------+ | 1 | abc | xyz | | 2 | bcd | stu | +------------+---------+------+ 2 rows in set (0.00 sec) Instead of querying to see if it exists then doing a second query to update, do it in one query using "INSERT .. ON DUPLICATE KEY"
    mysql> INSERT INTO hashtag (hashtag, link) VALUES ('abc', 'def') -> ON DUPLICATE KEY UPDATE link = values(link); Query OK, 2 rows affected (0.06 sec) mysql> select * from hashtag; +------------+---------+------+ | hashtag_id | hashtag | link | +------------+---------+------+ | 1 | abc | def | | 2 | bcd | stu | +------------+---------+------+ 2 rows in set (0.00 sec)
  18. Barand's post in Variable mySQLi prepared statement was marked as the answer   
    Using your current method (but with arrays and PDO) it becomes
    $databases = [ 'database1', 'database2', 'database3', 'database4', 'database5' ]; $baseSQL = "SELECT FirstName, LastName, Email, Mobile, PromoCode FROM <DB>.tablename WHERE (Email LIKE ?) OR (Mobile LIKE ?) OR (PromoCode LIKE ?) "; $queries = []; $params = []; $srch = isset($_GET['search']) ? '%' . $_GET['search'] . '%' : '%'; foreach ($databases as $dbname) { $queries[] = str_replace('<DB>', $dbname, $baseSQL ); array_push($params, $srch, $srch, $srch); } $sql = join("\nUNION\n", $queries); // build set of UNION queries /********** DEBUG ONLY _ DISPLAY QUERY **************/ echo '<pre>', $sql, '</pre>'; /****************************************************/ $stmt = $db->prepare($sql); $stmt->execute($params);
  19. Barand's post in Is this possible to do with php and mysql? was marked as the answer   
    My 0.02 worth
     
    Tables
    CREATE TABLE `users` ( `user_id` int(4) unsigned zerofill NOT NULL AUTO_INCREMENT, `username` varchar(45) DEFAULT NULL, `password` varchar(150) DEFAULT NULL, `email` varchar(150) DEFAULT NULL, PRIMARY KEY (`user_id`) ); CREATE TABLE `matrix` ( `matrix_id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) DEFAULT NULL, `sponsor_id` int(11) DEFAULT NULL, PRIMARY KEY (`matrix_id`), KEY `idx_matrix_user_id` (`user_id`), KEY `idx_matrix_sponsor_id` (`sponsor_id`) ); -- seed matrix with at least 1 record INSERT INTO matrix(user_id, sponsor_id) VALUES (null,1); This sample form adds a new user then inserts the user into the matrix table. If a sponsor is specified then that sponsors id is inserted, otherwise it is added to the first available sponsor (ie with less than 14 users)
     
    Just curious - why 14?
    <?php // Your PDO connection code goes here if ($_SERVER['REQUEST_METHOD']=='POST') { // NOTE : validation omitted for brevity $sql = "INSERT INTO users (username,password,email) VALUES (:user,:pass,:email)"; $stmt = $db->prepare($sql); $stmt->execute( [ 'user' => $_POST['name'], 'pass' => password_hash($_POST['pwd'], PASSWORD_DEFAULT), 'email' => $_POST['email'] ]); // get the id of the newly added user $userid = $db->lastInsertId(); // add new user into the matrix $sql = "INSERT INTO matrix (user_id, sponsor_id) SELECT @user as user , CASE WHEN @sponsor=0 THEN m.sponsor_id ELSE @sponsor END as sponsor FROM ( SELECT sponsor_id , COUNT(user_id) as tot FROM matrix WHERE sponsor_id IS NOT NULL GROUP BY sponsor_id HAVING tot < 14 ORDER BY sponsor_id LIMIT 1 ) m JOIN (SELECT @user := :user, @sponsor := :sponsor) init"; $stmt = $db->prepare($sql); $stmt->execute([ ':user' => $userid, ':sponsor' => $_POST['sponsor'] ]); } function userOptions($db, $current=0) { $sql = "SELECT user_id , username FROM users ORDER BY username"; $res = $db->query($sql); $opts = '<option value="0">--No sponsor specified--</option>'; foreach ($res as $r) { $opts .= "<option value='$r[user_id]'>$r[username]</option>\n"; } return $opts; } function currentUsers($db) { $sql = "SELECT u1.user_id , u1.username , GROUP_CONCAT(u2.user_id ORDER BY u2.user_id SEPARATOR ' | ') as users FROM matrix m INNER JOIN users u1 ON m.sponsor_id = u1.user_id INNER JOIN users u2 ON m.user_id = u2.user_id GROUP BY u1.user_id ORDER BY u1.user_id"; $res = $db->query($sql); $usrs = ''; foreach ($res as $r) { $usrs .= "<tr><td>$r[user_id]</td><td>$r[username]</td><td>$r[users]</td></tr>\n"; } return $usrs; } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>codeword_entry</title> <meta name="author" content="Barry Andrew"> <style type="text/css"> body { font-family: sans-serif; font-size: 10pt; } fieldset { padding: 15pt; background-color: #ccc; } legend { background-color: black; color: white; padding: 3px; } table { font-family: sans-serif; font-size: 10pt; border-spacing: 1px; min-width: 700px; } th { background-color: black; color: white; padding: 5px 3px; } td { padding: 3px; } </style> </head> <body> <h1>Add New User</h1> <form action="" method='POST'> <fieldset> <legend>User details</legend> User name <input type="text" name="name" size="40"><br> Password <input type="password" name="pwd" size="40"><br> Email <input type="text" name="email" size="50"> </fieldset> <fieldset> <legend>Sponsor</legend> Sponsor <select name="sponsor"><?=userOptions($db)?></select> </fieldset> <input type="submit" name="btnSub" value="Submit"> </form> <hr> <h2>Current Users</h2> <table> <tr><th>ID</th><th>User name</th><th>Sponsored Users</th></tr> <?=currentUsers($db)?> </table> </body> </html>
  20. Barand's post in if row exists update else insert was marked as the answer   
    Set a UNIQUE index on phone. Tablets can all have null values.
    EG
    CREATE TABLE `customers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `fullName` varchar(50) DEFAULT NULL, `phone` varchar(45) DEFAULT NULL, `pin` int(11) DEFAULT NULL, `device` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `idx_customers_phone` (`phone`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8; mysql> select * from customers; +----+----------+----------+------+--------+ | id | fullName | phone | pin | device | +----+----------+----------+------+--------+ | 1 | Cust_1 | 12346789 | 1234 | phone | | 2 | Cust_2 | 12356789 | 3456 | phone | | 3 | Cust_3 | 12366789 | 5678 | phone | | 4 | Cust_4 | NULL | NULL | tablet | | 5 | Cust_5 | NULL | NULL | tablet | +----+----------+----------+------+--------+ INSERT INTO customers (fullname,phone,pin,device) VALUES ('Cust_6', 12346789, 1010, 'phone') ON DUPLICATE KEY UPDATE pin = 1010; mysql> select * from customers; +----+----------+----------+------+--------+ | id | fullName | phone | pin | device | +----+----------+----------+------+--------+ | 1 | Cust_1 | 12346789 | 1010 | phone | <-- updated | 2 | Cust_2 | 12356789 | 3456 | phone | | 3 | Cust_3 | 12366789 | 5678 | phone | | 4 | Cust_4 | NULL | NULL | tablet | | 5 | Cust_5 | NULL | NULL | tablet | +----+----------+----------+------+--------+
  21. Barand's post in Best guess date from messy string. was marked as the answer   
    Provided that you can spell "February", only two of those formats do not work

    $dates = [ 'feb 21, 1999', 'February 21, 1999', '02/21/99', '2/21/99', '99/2/21', '2-21-1999', '19990221', 'sun, Feb 21, 1999', 'Sunday February 21, 1999' ]; echo '<pre>'; foreach ($dates as $dstr) { printf("%-30s%-15s%s\n", $dstr, date('Y-m-d', strtotime($dstr)), strtotime($dstr)==0 ? 'X' : '' ); } Outputs
    feb 21, 1999 1999-02-21 February 21, 1999 1999-02-21 02/21/99 1999-02-21 2/21/99 1999-02-21 99/2/21 1970-01-01 X 2-21-1999 1970-01-01 X 19990221 1999-02-21 sun, Feb 21, 1999 1999-02-21 Sunday February 21, 1999 1999-02-21 For rogue formats you can always use DateTime::createFromFormat()
  22. Barand's post in mySQLi statement for multiple databases was marked as the answer   
    Prefix the table name with the database name
    $sql = "SELECT ID, FirstName, Last Name, Email, Mobile, PromoCode FROM database1.table1 WHERE (Email LIKE ?) OR (Mobile LIKE ?) OR (PromoCode LIKE ?) UNION SELECT ID, FirstName, Last Name, Email, Mobile, PromoCode FROM database2.table1 WHERE (Email LIKE ?) OR (Mobile LIKE ?) OR (PromoCode LIKE ?) "; Databases must be on the same server.
  23. Barand's post in Hello A-Z Help was marked as the answer   
    try
    foreach (range('A','Z') as $alpha) { echo "<li data-text='$alpha'>$alpha</li>\n"; }
  24. Barand's post in Sort TEXT values as INT was marked as the answer   
    Looks like the "space" is some other whitespace character.
     
    What does
    SELECT HEX(price) as hexprice; give you?
  25. Barand's post in Coding a nested serialized PHP array was marked as the answer   
    Yes - it has been serialized twice.
    Serialize the array into a string
    Serialize the resulting string
     
    To unravel it, unserialize twice
    print_r( unserialize(unserialize('s:287:"a:8:{s:5:"price";a:2:{s:5:"value";s:5:"38000";s:8:"original";s:0:"";}s:17:"custom_tax_inside";s:0:"";s:15:"custom_tax_page";s:0:"";s:8:"city_mpg";a:1:{s:5:"value";s:0:"";}s:11:"highway_mpg";a:1:{s:5:"value";s:0:"";}s:12:"custom_badge";s:0:"";s:5:"video";s:0:"";s:10:"short_desc";s:0:"";}"'))); Gives
    Array ( [price] => Array ( [value] => 38000 [original] => ) [custom_tax_inside] => [custom_tax_page] => [city_mpg] => Array ( [value] => ) [highway_mpg] => Array ( [value] => ) [custom_badge] => [video] => [short_desc] => )
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.