So I am quite new to using PDO and although I have to it to work using static settings I would like to be able to change the table name in a statement.   and saw the highly up voted answer. So I attempted to recreate a simple version which would just dump all the information within a column.  Question: Why is my edited version of that persons example not work and return this error below.     Fatal error: Uncaught exception 'PDOException' with message   'SQLSTATE[42000]: Syntax error or access violation: 1064 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 '' at line 1' in   C:\xampp\htdocs\ *****\database.php:84 Stack trace: #0   C:\xampp\htdocs\ *****\database.php(84): PDOStatement->execute() #1   C:\xampp\htdocs\ *****\database.php(88): buildQuery(1) #2 {main}   thrown in C:\xampp\htdocs\ *****\database.php on line 84   The code from the example linked with my small alterations.  function buildQuery( $get_var )          {             switch($get_var)             {                 case 1:                     $tbl = `r16.7`;                     break;             }             global $db;             $sql = "SELECT * FROM $tbl";             $stmt = $db-&gt;prepare($sql);              $stmt-&gt;execute();             $result = $sth-&gt;fetchAll(PDO::FETCH_COLUMN, 1);             var_dump($result);         }         buildQuery(1);
213
Why can't I pass the table name to a prepared PDO statement?  $stmt = $dbh-&gt;prepare('SELECT * FROM :table WHERE 1'); if ($stmt-&gt;execute(array(':table' =&gt; 'users'))) {     var_dump($stmt-&gt;fetchAll()); }   Is there another safe way to insert a table name into a SQL query? With safe, I mean that I don't want to do  $sql = "SELECT * FROM $table WHERE 1"
92236
I have an xml file which I would like to create a form/table around to add, edit and delete records using PHP.  Currently I use simpleXML to load the XML file, and display its content on various pages.  Is there any way I can create a table that shows all results, and allows me to either edit or delete that particular row of the table which represents a full record within the XML file.    When clicking edit I would like the details from the record to appear in a form which the user can change and then save out, updating the XML file and the corresponding web page.  I need this done in PHP, preferably using SimpleXML, though open to suggestions of other ways to do this with PHP.  Cheers
103134
I have come to the conclusion that my PHP installation and my MySQL installation are not getting along; I’m working on making my first web page that uses MySQL for content, but after two days, man pages, online documentation, and dozens of tutorials, I just can’t get the PHP/MySQL part to work.  I have an established home web server (I am the only admin/user) that runs Apache and hosts my web pages.  I have MySQL installed, and was able to create and query a database through Terminal.  I have PHP installed, and can use echo to print text to the document.  When I work with MySQL however, everything changes…  I have a page that contains initialization stuff in .  contains a few paragraphs of hardcoded HTML and then PHP code to access MySQL.  When I first loaded the page, all that resulted was a blank page.  I commented out the PHP section and reloaded to confirm that the plain HTML still worked, which it did.  Therefore, some part of PHP was keeping any of the page from ever loading.    To begin troubleshooting my code, I left all of the PHP code commented except the following code for the server connection, which is adapted from several different tutorials:  &lt;? echo("&lt;p&gt;PHP is working&lt;/p&gt;");  $ses = mysql_connect("localhost","username","password"); if(!$ses){  echo("&lt;p&gt;Connection to content server failed.&lt;/p&gt;");  exit(); } echo("&lt;p&gt;Database Connected&lt;/p&gt;"); ?&gt;   When the page is loaded, the beginning HTML loads in addition to a paragraph reading “PHP is working” but neither the failure or success message appear.  I removed the If structure from the code - so that only two echos and the mysql_connect remained – and got the same result.    It seems that the mysql_connect feature is causing the server to stop loading the code when it is run, but I’m out of ideas for how to fix it.  For the record: I’ve modified the php.ini file to include the “connection = msql.so” line, and I’m using MySQL 5.5, Apache 2.2.22, PHP 5.3.10, Ubuntu 12.04.  Also, both my router and modem have been configured to forward port 3306 to the server – though I don’t see how that should be necessary – and my MySQL username and password have been triple checked and are identical to the ones that I use successfully in Terminal.  What am I missing?
91517
public static void handleCaseComment(CaseComment caseComment) {    User[] users = [SELECT LastName FROM User WHERE Id = caseComment.CreatedById LIMIT 1]; }   This gives me the following error:  unexpected token: 'caseComment.CreatedById'   How do I use the value of the variable caseComment.CreatedById in a SELECT statement?
13630
I have a simple query:  SELECT u_name AS user_name FROM users WHERE user_name = "john";   I get Unknown Column 'user_name' in where clause.  Can I not refer to 'user_name' in other parts of the statement even after select 'u_name as user_name'?
74983
I'm writing a php app to access a MySQL database, and on a tutorial, it says something of the form  mysql_connect($host, $user, $pass) or die("could not connect");   How does PHP know that the function failed so that it runs the die part? I guess I'm asking how the "or" part of it works. I don't think I've seen it before.
108487
I have the code below (I've included what I believe are all relevant sections):  private String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = ? AND VAL_@ = ?;"; public bool read(string id) {     level = -1;     MySqlCommand m = new MySqlCommand(readCommand);     m.Parameters.Add(new MySqlParameter("", val1));     m.Parameters.Add(new MySqlParameter("", val2));     MySqlDataReader r = m.ExecuteReader();     if (r.HasRows)         level = Convert.ToInt32(r.GetValue(0).ToString());     r.Close();     return true; }   When I run this, I get an IndexOutOfBoundsException on adding the first parameter. What have I done wrong?
42684
I know there is a question  but I checked its answers and it didn't help. I'm just learning developing modules for Drupal so maybe it's something really stupid but I have no idea...  My hook (in testModule4.install):  function testModule4_update_7001() {  $schema['testModule4_table'] = array(     'description' =&gt; 'TODO: Description',     'fields' =&gt; array(         'main_id' =&gt; array(             'description' =&gt; 'TODO: Description.',             'type' =&gt; 'serial',             'not null' =&gt; TRUE,         ),         'settings' =&gt; array(             'description' =&gt; 'TODO: Description',             'type' =&gt; 'text',             'not null' =&gt; FALSE,         ),         'uid' =&gt; array(             'description' =&gt; 'TODO: Description',             'type' =&gt; 'int',             'not null' =&gt; FALSE,         ),         'created' =&gt; array(             'description' =&gt; 'TODO: Description',             'type' =&gt; 'int',             'not null' =&gt; FALSE,         ),         'changed' =&gt; array(             'description' =&gt; 'TODO: Description',             'type' =&gt; 'int',             'not null' =&gt; FALSE,         ),     ),     'primary key' =&gt; array('main_id'), );  db_create_table('testModule4_table', $schema['testModule4_table']);  }   My module is working just fine. The schema_version of module in database is 0 but update.php just cannot see it. What can be the cause of that? :/ I was trying clearing cache and reenabling a module but without success. I just don't know where to search for source of the problem. If you need more data, just comment :/ .  Edit:  I created simple module:  testModule.module:  &lt;?php   function testModule_myform($delta = "") {      $form['something'] = array(         '#type' =&gt; 'markup',         '#markup' =&gt; 'Something',     );     return $form; }    /**  * Implements hook_menu();  */  function testModule_menu() {     $items["test/test"] = array(         'title' =&gt; 'testModule',         'description' =&gt; 'TODO: Description',         'page callback' =&gt; 'drupal_get_form',         'page arguments' =&gt; array('testModule_myform'),         'access callback' =&gt; TRUE,      );     return $items; }   testModule.info:  name = testModule description = Test module for Drupal experiments. package = CustomTest core = 7.x   testModule.install:  function testModule_update_7001() {     drupal_set_message('It works!');     print 'Show something!'; }   And it still ignores this hook... Is it officially a Drupal bug and I need to reinstall the whole Drupal? >_&lt;
44862
I have a problem binding booleans using mysqli_stmt::bind_param in PHP5. The SQL query is the following: insert into `nvp_notes` (subject,messageid,receivedate,read) values (?,?,?,?)  Where 'read' is a tinyint, either 0 or 1, as I've had issues with bit using mysqli. So the types that I list in bind_param are: $stmt-&gt;bind_param('sdsd', ...);  I've also tried 'sdsb' and 'sdss' but nothing seems to work, and I always get the message:  Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement  When I remove the read field in the statement everything works fine. I've run out of ideas with this one. Surely bind_param works with booleans?
46938
I am trying to execute my PHP code, which calls two MySQL queries via mysqli, and get the error "Commands out of sync; you can't run this command now".  Here is the code I am using  &lt;?php $con = mysqli_connect("localhost", "user", "password", "db"); if (!$con) {     echo "Can't connect to MySQL Server. Errorcode: %s\n". Mysqli_connect_error();     exit; } $con-&gt;query("SET NAMES 'utf8'"); $brand ="o"; $countQuery = "SELECT ARTICLE_NO FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE % ? %"; if ($numRecords = $con-&gt;prepare($countQuery)) {     $numRecords-&gt;bind_param("s", $brand);     $numRecords-&gt;execute();     $data = $con-&gt;query($countQuery) or die(print_r($con-&gt;error));     $rowcount = $data-&gt;num_rows;     $rows = getRowsByArticleSearch("test", "Auctions", " ");     $last = ceil($rowcount/$page_rows); }  else {  print_r($con-&gt;error); } foreach ($rows as $row) {     $pk = $row['ARTICLE_NO'];     echo '&lt;tr&gt;' . "\n";     echo '&lt;td&gt;&lt;a href="#" onclick="updateByPk(\'Layer2\', \'' . $pk . '\')"&gt;'.$row['USERNAME'].'&lt;/a&gt;&lt;/td&gt;' . "\n";     echo '&lt;td&gt;&lt;a href="#" onclick="updateByPk(\'Layer2\', \'' . $pk . '\')"&gt;'.$row['shortDate'].'&lt;/a&gt;&lt;/td&gt;' . "\n";     echo '&lt;td&gt;&lt;a href="#" onclick="deleterec(\'Layer2\', \'' . $pk . '\')"&gt;DELETE RECORD&lt;/a&gt;&lt;/td&gt;' . "\n";     echo '&lt;/tr&gt;' . "\n"; } function getRowsByArticleSearch($searchString, $table, $max) {     $con = mysqli_connect("localhost", "user", "password", "db");     $recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE '%?%' ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max;     if ($getRecords = $con-&gt;prepare($recordsQuery)) {         $getRecords-&gt;bind_param("s", $searchString);         $getRecords-&gt;execute();         $getRecords-&gt;bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate);         while ($getRecords-&gt;fetch()) {             $result = $con-&gt;query($recordsQuery);             $rows = array();             while($row = $result-&gt;fetch_assoc()) {                 $rows[] = $row;             }             return $rows;         }     } }   I have tried reading up on this, but I am unsure of what to do. I have read about store result and free result, however these have made no difference when using them. I am unsure at exactly which point this error is being caused, and would like to know why it is being caused, and how to fix it.  Going by my debug statements, the first if loop for countQuery is not even being entered, because of an error in my sql syntax near near '% ? %'. However if I just select * instead of trying to limit based on a LIKE clause, I still get the command out of sync error.
54951
I am attempting to create a stored procedure where a table name is passed as a parameter, as well as updating contents of the table. Here is my code I have so far.  SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE TableSelect     @TableName varchar(100) AS BEGIN     SET NOCOUNT ON;      Declare @String varchar(100)     SELECT @String = 'Update '     SELECT @String = @String + @TableName     SELECT @String = @String + 'Set Internet = 1'      EXEC (@String)  END GO   When I attempt to execute by this command:  EXEC TableSelect 'Waterford';   I get the error:  Msg 102, Lvevl 15, State 1, Line 1 Incorrect syntax near 'Internet'.   Any help would be great. FYI, the column Internet, is just a bit so 0/1 or False/True. Thanks
18011
Is there a way to get the raw SQL string executed when calling PDOStatement::execute() on a prepared statement? For debugging purposes this would be extremely useful.
3825
I am simply trying to return the rows from a table in my db but i keep getting this error thrown back at me no matter what I do "Fatal error: Unsupported operand types in C:\xampp\htdocs\d7\includes\form.inc on line 1009". Am I missing a argument or something?  This is my function  Hook menu  function auto_form_menu() { $items = array(); $items['admin/config/auto_form'] = array(     'title' =&gt; 'My Module',     'description' =&gt; 'description',     'page callback' =&gt; 'drupal_get_form',     'page arguments' =&gt; array('auto_form_records'),     'access arguments' =&gt; array('administer site configuration'),     'file' =&gt; 'auto_form.admin.inc' );  $items['admin/config/auto_form/manage'] = array(     'title' =&gt; 'My Module',     'type' =&gt; MENU_DEFAULT_LOCAL_TASK,     'description' =&gt; 'description',     'weight' =&gt; -10, ); return $items; }   'auto_form.admin.inc'  function auto_form_records() {   $header = array('First Name', 'Last Name');    $dbresult = db_query("SELECT first, last FROM {auto}");      $rows = array();     foreach ($dbresult as $dbrow) {         $rows[] = array(         $dbrow-&gt;first,         $dbrow-&gt;last       );     }     return $output = theme('table', array('header' =&gt; $header, 'rows' =&gt; $rows)); }   Updated Code:  Any help is appreciated seeing how I am completely lost on figuring this out.
21375
I want to write a select statement that with some fixed columns and dynamic columns. here Dynamic Columns names are the rows in another table.  I have tried this but getting error. Please tell me where my error is  set @sql=(Select subject from tbl_subjects where C_Id=22); SELECT      ta.rollno,     ta.StdNm,     tc.C_Name,     @sql FROM     tbl_cmarks tm,     tbl_admission ta,     tbl_classes tc WHERE     tm.Cid = tc.C_Id         AND ta.rollno = tm.rollno         AND tm.Cid = 22 and tm.Examid=9    Mysql showing:     Error Code: 1242. Subquery returns more than 1 row   Could any one tell me how to do this in mysql?
58172
This query works for me when I tried in PG admin query tool:    UPDATE bankdetails SET bank_details = 'mysore' ,"PAN"= 123,bank_acc = 456,                        "UAN"=789,tax = 'myy' WHERE  user_id = 79; INSERT INTO bankdetails (user_id,bank_details,"PAN",bank_acc,"UAN",tax)        SELECT 79,'mysore',123,456,789,'myy'        WHERE NOT EXISTS (SELECT 1 FROM bankdetails WHERE user_id=79);   Later I implemented in my code like this:  db.query('UPDATE bankdetails SET bank_details = $2 ,"PAN"= $3,bank_acc = $4,"UAN"=$5,tax = $6 WHERE user_id = $1; INSERT INTO bankdetails (user_id,bank_details,"PAN",bank_acc,"UAN",tax) SELECT $1,$2,$3,$4,$5,$6 WHERE NOT EXISTS (SELECT 1 FROM bankdetails WHERE user_id = $1);', [companyuser.rows[0]._id, data.bankDetails.bank_details, data.bankDetails.PAN, data.bankDetails.bank_acc, data.bankDetails.UAN, data.bankDetails.tax],function(err,bank) {                  if (err) return callback(new Error('error')); })   it says:     cannot insert multiple commands into a prepared statement   Can some one guide me here?
73
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to , 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 like value'); DROP TABLE table;--, and the query becomes:  INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')   What can be done to prevent this from happening?
108573
I am getting below error while importing the dump,     ERROR 3105 (HY000) at line 82: The value specified for generated   column 'column_name' in table 'table_name' is not allowed.   When I describe the table with error, there are some generated columns in it.     option_type         | varchar(45)  | YES  | MUL | NULL    | VIRTUAL   GENERATED   What is the correct command to use when taking mysql dump for the database contains generated column?  MySQL server source and destination version:     mysqld Ver 5.7.26 for Linux on x86_64 (MySQL Community Server (GPL))   MariaDB mysqldump CLI version:     mysqldump Ver 10.17 Distrib 10.3.12-MariaDB, for Linux (x86_64)