PHP variable in SQLite query

Asked
Active3 hr before
Viewed126 times

8 Answers

variable
90%

I'm a beginner with web-related coding and I'm trying to make a web-interface from where I can read and write to the sqlite database. My current problem is implementing a PHP-variable ($inNodeID) to sqlite query:,Problem is because of you have enclosed variable $inNodeID. If a variable is enclosed in Quotes PHP behave in different ways based on the Quote thats used. PHP evaluates a variable only when its enclosed in Double quotes, if its used with Single Quote then PHP treats it as a STRING. ,If I replace the variable in query to the value of the variable ("ID007") everything seems to work. So what is wrong with my syntax in this manner?,bind your php variable with the previous step "imaginary word" like this: $statement -> bindValue(':imaginary_word', $php_variable);

Here you go:

$result = $db - > prepare('SELECT * FROM data WHERE NodeID = ?');
$result - > execute(array($inNodeID));
$data = $result - > fetchAll();

foreach($data as $row)
   ...
load more v
88%

SQLite3::query — Executes an SQL query, The SQL query to execute. ,Example #1 SQLite3::query() example, Returns an SQLite3Result object, or false on failure.

load more v
72%

The bind_param() binds a parameter to a statement variable. It can be used to handle multiple rows. , In the example, we insert two rows into a table with a parameterized statement. To bind the placeholders, we use the bind_param() method. , This is a PHP programming tutorial for the SQLite version 3 database. It covers the basics of SQLite programming with the PHP language. , We create an SQLite3 object and open an SQLite3 database connection.

For working with the SQLite database, we can install the sqlite3 command line tool or the SQLite browser GUI.

$ php - v
PHP 7.2 .11(cli)(built: Oct 10 2018 02: 39: 52)(ZTS MSVC15(Visual C++2017) x86)
Copyright(c) 1997 - 2018 The PHP Group
Zend Engine v3 .2 .0, Copyright(c) 1998 - 2018 Zend Technologies
load more v
65%

Stephan is correct, your problem has nothing to do with SQL or SQLite. It is not even a problem of the PHP wrapper around SQLite, but purely misunderstanding of PHP variable scope.,I have created a PHP program to generate INSERT queries. However the code to actually insert the record into the database will not work. Attached is the full process. The query produced works just fine if executed in 'sqlitebrowser'.,You need to send this to the PHP forums. This forum is only for the sqlite C library and related components, not the hundred+ 3rd-party wrappers which wrap that library.,// Taken From SQLite - PHP INSERT Operation and turned into funtion insertRecord($sql) // https://www.tutorialspoint.com/sqlite/sqlite_php.htm

// From SQLite - PHP INSERT Operation // https://www.tutorialspoint.com/sqlite/sqlite_php.htm

   class MyDB extends SQLite3 {
      function __construct() {
         global $database;
         $this - > open($database); // optumRx.db
      }

// =================================================================

	$str2. = "'".$recArray['Cost'][$i].
	"',"; // main part of script dynamicaly building the query
	$str2. = "'".$recArray['ReFills'][$i].
	"');";
	$query = $str.$str2;
	fwrite($fh, $query.
	   "\n\n"); // write query to log 
	fwrite($fh, "\n  ========================================================\n\n");
	insertRecord($query); // call to function to INSERT query to database 
	$str2 = " VALUES( "; // begin next record
	}
load more v
75%

SELECT COUNT(*) AS count_ratings, AVG(rating) AS ave_rating FROM ratings WHERE tour_id = 22,This stops the same user rating a tour twice. Also you can get the COUNT of rating and AVG of rating via a simple sql statement. …,This stops the same user rating a tour twice. Also you can get the COUNT of rating and AVG of rating via a simple sql statement. EG:,Hey guise, I have a uni assignment; setting up backend code for a tour company website. Everything's gone swimmingly but I've run into issues implementing a system for rating the tour packages.

My code is below.

        if ($_POST[Tour_Rating] >= 1 && $_POST[Tour_Rating] <= 5) {
           try {
              $rating = $dbh - > query("SELECT TotalRatings FROM Tours WHERE Tour_Id = '$_POST[Tour_Id]'");
              $count = $dbh - > query("SELECT RatingNo FROM Tours WHERE Tour_Id = '$_POST[Tour_Id]'");

              $postRating = intval($_POST[Tour_Rating]);
              $ratings = intval($rating);
              $ratings += $postRating;

              $counts = intval($count);
              ++$counts;

              $avgRatings = $ratings / $counts;
              $avgRating = intval($avgRatings);

           } catch (exception $e) {
              echo "sql queries failed";
              echo $e;
           }

           $sql = "UPDATE Tours SET TotalRatings = '$ratings', RatingNo = '$counts', Tour_Rating = '$avgRating' WHERE Tour_Id = '$_POST[Tour_Id]' ";

           $dbh - > exec($sql)
        }
40%

Connect to the SQLite database using the PDO object.,Home » SQLite PHP » SQLite PHP: Querying Data,Loop through the result set using the fetch() method of the PDOStatement object and process each row individually.,First, we called the query() method of the PDO object to query the data from the projects table. The query() method returns PDOStatement object, which is $stmt.

See the following getProjects() method.

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
/**
 * Get all projects
 * @return type
 */
public
function getProjects() {
   $stmt = $this - > pdo - > query('SELECT project_id, project_name '
      .
      'FROM projects');
   $projects = [];
   while ($row = $stmt - > fetch(\PDO::FETCH_ASSOC)) {
      $projects[] = [
         'project_id' => $row['project_id'],
         'project_name' => $row['project_name']
      ];
   }
   return $projects;
}
Code language: PHP(php)
load more v
22%

< ? php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "", "demo");

// Check connection
if ($mysqli === false) {
   die("ERROR: Could not connect. ".$mysqli - > connect_error);
}

// Escape user inputs for security
$first_name = $mysqli - > real_escape_string($_REQUEST['first_name']);
$last_name = $mysqli - > real_escape_string($_REQUEST['last_name']);
$email = $mysqli - > real_escape_string($_REQUEST['email']);

// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('$first_name', '$last_name', '$email')";
if ($mysqli - > query($sql) === true) {
   echo "Records inserted successfully.";
} else {
   echo "ERROR: Could not able to execute $sql. ".$mysqli - > error;
}

// Close connection
$mysqli - > close(); ?
>
60%

The semicolon at the end of an SQL statement is optional when submitting a query string to exec() or query()., SQL comments start with a double-dash, and continue to the end of the line. They are ignored by the database, but are used below to add some commentary to the examples., The exec() and query() functions both submit a string containing an SQL statement (see below) to the database for processing. The difference is that exec() doesn’t return a value, and thus is most appropriate for SQL statements like CREATE, INSERT, UPDATE, DELETE or DROP. But query() is used for SELECT statements, which return values from the database. The $result value returned is another type of PHP object, which you use for accessing the actual data returned by the query., The fetchArray() function returns one row from the results returned by query(), or false if there are no (more) rows. The $row value returned is an array with one element for each column in the row returned. Use can index into that array using the name of a database table column. See examples below.


$db_handle = new SQLite3($filename);
$db_handle - > exec($query_string);
$result = $db_handle - > query($query_string);
$row = $result - > fetchArray();
load more v

Other "variable-undefined" queries related to "PHP variable in SQLite query"