Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

WikiQuora

WikiQuora Logo WikiQuora Logo

WikiQuora Navigation

Search
Ask A Question

Mobile menu

Close
Ask A Question
  • Home
  • Add group
  • Feed
  • User Profile
  • Communities
  • Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
Home/sql

WikiQuora Latest Questions

Saralyn
  • 1
SaralynTeacher
Asked: May 6, 2025

How do SQL and database systems deal with timezones in date data?

  • 1

Most database engines normalize to GMT/UTC for storage (and typically store “seconds since some time 0” as timezoneless numbers in actual date or datetime/timestamp fields) and have a notion of a “default” time zone for date ...

databasedateJavaoraclesqltimetimezone
0
  • 0 0 Answers
  • 99 Views
Answer
W3spoint99
  • 0
W3spoint99Begginer
Asked: December 25, 2024In: MySQL

How to create pivot table in mysql?

  • 0

If I have a MySQL table looking something like this: company_name action pagecount Company A PRINT 3 Company A PRINT 2 Company A PRINT 3 Company ...

mysqlpivotpivot-tablesqltable
  1. Saralyn
    Saralyn Teacher
    Added an answer on December 25, 2024 at 10:21 am

    Many people just use a tool like MSExcel, OpenOffice or other spreadsheet-tools for this purpose. This is a valid solution, just copy the data over there and use the tools the GUI offer to solve this. But... this wasn't the question, and it might even lead to some disadvantages, like how to get theRead more

    Many people just use a tool like MSExcel, OpenOffice or other spreadsheet-tools for this purpose. This is a valid solution, just copy the data over there and use the tools the GUI offer to solve this.

    But… this wasn’t the question, and it might even lead to some disadvantages, like how to get the data into the spreadsheet, problematic scaling and so on.

    The SQL way…

    Given his table looks something like this:

    CREATE TABLE `test_pivot` (
      `pid` bigint(20) NOT NULL AUTO_INCREMENT,
      `company_name` varchar(32) DEFAULT NULL,
      `action` varchar(16) DEFAULT NULL,
      `pagecount` bigint(20) DEFAULT NULL,
      PRIMARY KEY (`pid`)
    ) ENGINE=MyISAM;
    

    Now look into his/her desired table:

    company_name    EMAIL   PRINT 1 pages   PRINT 2 pages   PRINT 3 pages
    -------------------------------------------------------------
    CompanyA        0       0               1               3
    CompanyB        1       1               2               0
    

    The rows (EMAIL, PRINT x pages) resemble conditions. The main grouping is by company_name.

    In order to set up the conditions this rather shouts for using the CASE-statement. In order to group by something, well, use … GROUP BY.

    The basic SQL providing this pivot can look something like this:

    SELECT  P.`company_name`,
        COUNT(
            CASE 
                WHEN P.`action`='EMAIL' 
                THEN 1 
                ELSE NULL 
            END
        ) AS 'EMAIL',
        COUNT(
            CASE 
                WHEN P.`action`='PRINT' AND P.`pagecount` = '1' 
                THEN P.`pagecount` 
                ELSE NULL 
            END
        ) AS 'PRINT 1 pages',
        COUNT(
            CASE 
                WHEN P.`action`='PRINT' AND P.`pagecount` = '2' 
                THEN P.`pagecount` 
                ELSE NULL 
            END
        ) AS 'PRINT 2 pages',
        COUNT(
            CASE 
                WHEN P.`action`='PRINT' AND P.`pagecount` = '3' 
                THEN P.`pagecount` 
                ELSE NULL 
            END
        ) AS 'PRINT 3 pages'
    FROM    test_pivot P
    GROUP BY P.`company_name`;
    

    This should provide the desired result very fast. The major downside for this approach, the more rows you want in your pivot table, the more conditions you need to define in your SQL statement.

    This can be dealt with, too, therefore people tend to use prepared statements, routines, counters and such.

    Some additional links about this topic:

    • http://anothermysqldba.blogspot.de/2013/06/pivot-tables-example-in-mysql.html
    • http://www.codeproject.com/Articles/363339/Cross-Tabulation-Pivot-Tables-with-MySQL
    • http://datacharmer.org/downloads/pivot_tables_mysql_5.pdf
    • https://codingsight.com/pivot-tables-in-mysql/
    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 312 Views
Answer
W3spoint99
  • 0
W3spoint99Begginer
Asked: December 25, 2024In: Programmers

How to prevent SQL injection in PHP?

  • 0

If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example: $unsafe_variable = $_POST['user_input']; mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')"); That’s because the user can input something ...

mysqlphpsecuritysqlsql-injection
  1. Saralyn
    Saralyn Teacher
    Added an answer on December 25, 2024 at 10:08 am

    The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fulRead more

    The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don’t fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

    You basically have two options to achieve this:

    1. Using PDO (for any supported database driver):
      $stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');
      $stmt->execute([ 'name' => $name ]);
      
      foreach ($stmt as $row) {
          // Do something with $row
      }
      
    2. Using MySQLi (for MySQL):
      Since PHP 8.2+ we can make use of execute_query() which prepares, binds parameters, and executes SQL statement in one method:

      $result = $db->execute_query('SELECT * FROM users WHERE name = ?', [$name]);
      while ($row = $result->fetch_assoc()) {
          // Do something with $row
      }
      

      Up to PHP8.1:

      $stmt = $db->prepare('SELECT * FROM employees WHERE name = ?');
      $stmt->bind_param('s', $name); // 's' specifies variable type 'string'
      $stmt->execute();
      $result = $stmt->get_result();
      while ($row = $result->fetch_assoc()) {
          // Do something with $row
      }
      

    If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.


    Correctly setting up the connection

    PDO

    Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

    $dsn = 'mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4';
    $dbConnection = new PDO($dsn, 'user', 'password');
    
    $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    In the above example, the error mode isn’t strictly necessary, but it is advised to add it. This way PDO will inform you of all MySQL errors by means of throwing the PDOException.

    What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

    Although you can set the charset in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.

    Mysqli

    For mysqli we have to follow the same routine:

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
    $dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
    $dbConnection->set_charset('utf8mb4'); // charset
    

    Explanation

    The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute, the prepared statement is combined with the parameter values you specify.

    The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.

    Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employees the result would simply be a search for the string "'Sarah'; DELETE FROM employees", and you will not end up with an empty table.

    Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

    Oh, and since you asked about how to do it for an insert, here’s an example (using PDO):

    $stmt = $db->prepare('INSERT INTO table (column) VALUES (:column)');
    $stmt->execute(['column' => $value]);
    

    Can prepared statements be used for dynamic queries?

    While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.

    For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

    // Value whitelist
    // $dir can only be 'DESC', otherwise it will be 'ASC'
    if (empty($dir) || $dir !== 'DESC') {
       $dir = 'ASC';
    }
    
    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 469 Views
Answer

Sidebar

Ask A Question
  • Popular
  • Answers
  • W3spoint99

    What is the difference between Promises and Observables?

    • 2 Answers
  • W3spoint99

    Can't bind to 'ngModel' since it isn't a known property ...

    • 2 Answers
  • W3spoint99

    How to prevent SQL injection in PHP?

    • 1 Answer
  • Saralyn
    Saralyn added an answer Learn Java if: ✅ You want to work on enterprise applications.… April 27, 2025 at 2:01 pm
  • Saralyn
    Saralyn added an answer AI is getting smarter, but replacing programmers entirely? That’s not… April 27, 2025 at 1:58 pm
  • Saralyn
    Saralyn added an answer Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature… January 17, 2025 at 2:03 pm

Trending Tags

AI angular application.properties arrays artificial intelligence coding how Java javascript machine learning mysql nullpointerexception php programmer python reactjs spring springboot sql string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

  • About US
  • Privacy Policy
  • Questions
  • Recent Questions
  • Web Stories

© 2025 WikiQuora.Com. All Rights Reserved