FAQ Database Discussion Community


How to use prepare() with dynamic column names?

php,sql,wordpress,prepared-statement
I have a function that takes an sql table column name string as a parameter, returns 1 string result: function myFunction($column_name) { return $wpdb->get_var($wpdb->prepare("SELECT %s FROM myTable WHERE user_id=%s", $column_name, $current_user->user_login)); } However, this code does NOT work, since with the nature of prepare, I can't use a variable for...

mysqli_prepare() Query working on localhost but not when uploaded online, variables on prepared statements

php,mysql,mysqli,prepared-statement
I appreciate your effort for taking the time to read my post and hopefully answer my problem. I am currently making the login system of an item inventory list for a client's website. I keep getting these errors online when testing the login form : Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of...

Does SQLite3 have prepared statements in Node.js?

sql,node.js,express,sqlite3,prepared-statement
From the npm docs, only visible prepared statements are for insert. Does these prepared statement work for Select, update, and delete? I tried for select, there isn't a .each function where the rows are called back. Anyone been able to do this or have links to resources, cause I can...

How to insert records faster

java,mysql,prepared-statement,sql-insert
I have to read records from CSV file and store them in Mysql database. I know about "LOAD DATA INFILE" but in my case I have to get single record from file, check if it is in valid format/length etc and then store it in database. // list to store...

How to populate a dropdown box using mysqli prepared statements (PHP)

php,mysqli,prepared-statement
I am trying to figure out how to populate a dropdown menu in a form with data from a MySQL table. I have found the PHP manual online to be a little helpful (http://php.net/manual/en/mysqli.prepare.php), but I am still not fully understanding it. Here is what I have so far... function...

Java Prepared Statements Not Entirely Working - MYSQL

java,mysql,servlets,prepared-statement
I am using Java Servlets to connect and insert data into my MYSQL database. I am currently using the following prepared statement: String query1 = "SELECT * FROM `user` WHERE `username` = ?;"; PreparedStatement stat1 = connection.prepareStatement(query1); stat1.setString(1, username); ResultSet result = stat1.executeQuery(); out.println("<h1> PREPARED STATEMENT WORKING </h1>"); Using this,...

Cassandra nodejs DataStax driver don't return newly added columns via prepared statement execution

node.js,cassandra,prepared-statement
After adding a pair of columns in schema, I want to select them via select *. Instead select * returns old set of columns and none new. By documentation recommendation, I use {prepare: true} to smooth JavaScript floats and Cassandra ints/bigints difference (I don't really need the prepared statement here...

PreparedStatement query to insert data into specific columns in a table

java,sql,jdbc,prepared-statement
I am trying to insert data into specific columns (5th and 6th) of a table. My PreparedStatement code is as follows: PreparedStatement pst1 = connection.prepareStatement("insert into CustomerPayment (End_Time,Paid) values (?,?) where PC_Used ='"+cmbpcname.getSelectedItem().toString()+"'"); pst1.setString(5,lblendtime.getText()); pst1.setString(6,lblamount.getText().substring(3,5)); pst1.execute(); Is this query right? I am getting error running that query. Any suggestion would...

Include a re-usable text block in query

mysql,sql,prepared-statement,reusability
I am looking for a solution to create a separate text-block (consisting of certain conditions) which I could create just once and later reference it inside a query: Example: Re-usable text-block (A1, B1, C1, D1 and G1 are actual column names): ------------- WHERE A1 > B1 and B1 < C1...

syntax error with prepared statements mysql/php [duplicate]

php,mysql,prepared-statement
This question already has an answer here: Syntax error due to using a reserved word as a table or column name in MySQL 1 answer Been messing around with this since last night at no avail. createOrder($website,(int)$nVotes,(int)$timeframe,$loggedInUser->email,$server,(int)$start,$referer); var_dumping these variables shows (earlier): string(2) "web1" string(2) "10" string(2) "10" string(23)...

Inserting multiple rows (single query) to MySQL in PHP: Prepare-Execute vs. Prepare-Bind-Execute

php,mysql,pdo,prepared-statement,prepare
I'm writing some PHP to accept an array of numbers and names in POST and insert them into a MySQL table (named Contacts_table) Here's the version that works fine without any error: <?php // Includes require_once 'Admin/Connector.php'; // Test if payload exists if($_POST){ // Read payload into arrays $ar =...

SQL Prepared Statement Exception

java,sql,prepared-statement
I cannot figure out what seems to be the problem with this code public boolean InsertFile(UserUpload userUpload){ try { con = connectToDB(); stmt = con.prepareStatement("INSERT INTO USERUPLOADS VALUES(?,?,?,?)"); stmt.setInt(1, getUploadId()); stmt.setString(2, userUpload.getFileName()); stmt.setString(3, userUpload.getFilePath()); stmt.setString(4, userUpload.getUserId()); stmt.executeUpdate(); return true; } catch (Exception e) { e.printStackTrace(); return false; } I am...

JAVA SQL assign all wildcards to null

java,sql,prepared-statement,wildcard
I currently have an sql string returned with the string wildcards marking null values. I am trying to find a way to set all of these wildcard values to null. After looking around, I have found a preparedStatement.setNull() method however it takes an index and the indexes of the wildcards...

What is the difference between the following to methods for bind_param PHP

php,prepared-statement
I'm just getting over using the singleton approach and am starting to get into prepared statements... I'm racking my brain on why one version of this works and one does not when, to me, they seem to be the same thing... I really want it to work the second way...

PHP insert into MySQL and record position number

php,mysqli,prepared-statement
Goal: Record the position order of each form item on insert. I'm allowing the user to dynamically add and delete form fields(that functionality is working with JS). For simplicity sake, the user designs their form to look like this: Form: Subtitle Paragraph Subtitle Image My database would contain a table...

Securing a static SQL query from SQL Injection

java,mysql,prepared-statement,sql-injection,fortify
I have an application which reads thousands of flat files containing database parameters and static SQL statements. In my java code i take the SQL statement and execute it. This is not acceptable to Fortify due to probable SQL Injection vulnerability. e.g. my flat file is something like below: query:...

Why does the mysqli bind function not handle my string correctly?

php,mysql,mysqli,prepared-statement
It took me like a month to figure out how make a session handler function work in PHP. I only had one problem, the bind_param function using i to fetch records instead of s. $stmt = $mysqli->prepare("SELECT data FROM session WHERE id = ?"); $stmt->bind_param('i', $id); $stmt->execute(); This $id is...

SQLException: Cannot submit statement in current context

jdbc,prepared-statement,callable-statement,voltdb
I encountered this exception when calling a stored procedure through a prepared statement, however, it works for callable statement. I am wondering if it is a must to use callable statement for invoking a stored procedure in voltdb? String sql = "{call get_city_by_country(?)}"; PreparedStatement stat = conn.prepareStatement(sql); stat.setString(1, "china"); ResultSet...

MySQLi prepare update not updating the database

php,mysql,mysqli,prepared-statement
As the title states, my MySQLi prepared update is not actually updating the database. I have checked the MySQL logs - no errors. Here is the code in question: public function update_tweet($tweet) { $prepared_update = $this->connection->prepare("UPDATE Tweets SET `text` = ?, `algo_score` = ?, `has_algo_score` = ?, `baseline_score` = ?,...

use sysdate as parameter to insert into database

java,oracle,prepared-statement
I have a prepareStatement that inserts a date value into the test table. The date value can be the value from a parameter or NULL. Now I want to insert the sysdate in database if the date value is null. I don't want to use new java.util.Date().getTime() since the time...

Unknown column 'v_plateno' in 'where clause' in Java

java,mysql,sql-update,prepared-statement
this is my Table vehicletlb ! Field Type v_branch varchar(255) NULL v_segment varchar(255) NULL v_company varchar(255) NULL v_name varchar(255) NULL v_plateno varchar(255) NULL v_seats int(11) NULL v_fuel varchar(255) NULL v_priceperkm int(11) NULL v_driver varchar(255) NULL Now I am trying to Update the table using Prepared Statement in Servlet. But unfortunately...

store_result() and get_result() in mysql returns false

php,mysql,return,prepared-statement
I made a code a few days ago including get_result() to receave the results from my database. Today I wantet to add to it and fix some errors. So I tried to use num_rows to see if anything were returned. But for this I had to use store_result(). And when...

Syntax Error on using DECLARE and prepared statement inside CREATE PROCEDURE

mysql,stored-procedures,syntax-error,prepared-statement
I am trying to work with MySQL prepared statements inside of a stored procedure. I have been trying to debug this CREATE code for a couple of hours, now frustrated. DELIMITER // DROP PROCEDURE IF EXISTS doSomething// CREATE PROCEDURE doSomething(IN tblname CHAR(32)) BEGIN DECLARE str1 TEXT DEFAULT ''; SET str1...

PDO Prepared statement insert 1 instead of string

php,mysql,pdo,prepared-statement
I have this query which no matter what $relocation['persons_id'] is, updates residents to 1. The following code will in this example echo 11,13, but set residents to 1: $query = $db->prepare('UPDATE `apartments` SET `residents` = :persons_id AND `occupation_date` = :occupation_date WHERE `id` = :apartments_id'); echo $relocation['persons_id']."<br>\n"; $query->bindParam(':persons_id', $relocation['persons_id']); $query->bindParam(':occupation_date', $relocation['occupation_date']);...

Turning mysql query into prepared statement

php,mysqli,prepared-statement
I'm trying to turn the below query into a prepared statement, but I'm having no luck so far. I've attached one of my attempts. The idea is I'm using this to check how many rows are returned using mysqli_num_rows afterward. $sql2=mysqli_query($bd, "SELECT address FROM member WHERE address='".$address."'"); This is my...

SQL Server Connection Pools with Prepared Statements and Transactions

c#,.net,transactions,sql-server-2012,prepared-statement
I'm hoping to leverage connection pooling in my .Net application, but have some concerns about support for prepared statements and transactions. Although it appears that the .Net framework provides the EnlistTransaction method to provide support for transactions with connection pools, I'm trying to determine if similar support exists for prepared...

PHP Prepared Statements handle duplicate entry

php,mysql,mysqli,error-handling,prepared-statement
I have a problem, I am not able to handle a duplicate entry with prepared statements. I want to end the program when a duplicate entry appears. This is what I have been trying to do: function insert_vulnerability ($CVE, $Description, $Date, $Score, $Type){ $conn = connection(); $stmt = $conn->prepare("INSERT INTO...

Java mysql prepared statement update not working

java,jdbc,prepared-statement
This is my code: ResultSet rs = statement.executeQuery("select * from page"); PreparedStatement updatepage = mySqlCon.prepareStatement("update enwiki.page set enwiki.page.Text = ? where page_id = ?"); int count = 0; while (rs.next()) { int id = rs.getInt("id"); String text = rs.getString("text"); if(text == null) text = ""; updatepage.setString(1, text); updatepage.setInt(2, id); if(count++...

PDO Transaction with Prepared Statements not working

php,mysql,pdo,transactions,prepared-statement
I have a PDO Transaction in which I'm trying to use prepared statements to run two queries on my database. They're both insert statements, they insert data from Facebook into two separate tables (named "player" and "bank"). The Facebook data is sent to this php script by an AJAX post....

Java - Pulling From Database With Prepared Statement

java,sql,prepared-statement
I'm having a problem returning a single record from my database. Every time I run the code it returns null. The code fails on the asterisked line below. My code is: public Map<String,Object> retrieveRecordById(String tableName, String column, int primaryKey) throws ClassNotFoundException, SQLException { Map<String,Object> record = null; PreparedStatement pStmt =...

Why can't I prepare this sql statement to set auto_increment?

mysql,prepared-statement
I want to set the auto_increment value for each column by first finding the max id value. I am referencing the code from this SO question. The mysql docs for prepared statements show a similar format, so I am confused. When I try running the prepare statement I get a...

How to return all the rows in this SQL while

php,mysqli,prepared-statement
The question being wide enough, I haven't found the answer on the forums, or at least not entirely. Being accustomed to use arrays, and not finding it practical in the long run, I decided to put myself in programming object. Here is my problem: When I run the SQL query...

Transfer parameter into a preparedStatement from list

java,jdbc,prepared-statement,postgresql-9.4
I've this preparesStatement: String insertSQL = "(INSERT INTO visit(Doc_Number, Pat_Number, to_timestamp(Date DD/MM/YYYY), Price) VALUES (?,?,?,?))" PreparedStatement pstvisit = conn.prepareStatement(insertSQL); And I'm tryind to do this: for (List<String> row : fileContents){ pstvisit.clearParameters(); pstvisit.executeUpdate("INSERT INTO VISIT (Doc_Number, Pat_Number, to_timestamp(Date DD/MM/YYYY), Price) VALUES (?, ?, ?, ?)"); FileContents read a file data with...

Possible Memory Leak with prepared statements?

php,sql,memory-management,memory-leaks,prepared-statement
Background: I am trying to learn prepared statements, and this one is throwing an error I would like to learn how to fix. The data in the Item table is inputted by users which is why I am using a prepared statement for this one as well, and well... the...

jpa namedquery with literals changed to prepared statement

jpa,prepared-statement,openjpa,named-query,sqlperformance
I have a jpa (openjpa-2.2.1) namedquery that has some hardcoded literals (ex: a.status <> 'X') - the problem is at runtime the generated query is actually a prepared statement (a.status <> ?) Is there a way to force JPA run the query as is? (i would like to keep it...

How to use 'or' inside mysqli prepare statement query

php,mysql,mysqli,prepared-statement
I'm new to mysqli prepare statement and was surprised to find out the || doesn't work as expected in mysqli prepare statement query. I have a function which check whether the user registered, and its evaluation should be based upon the unique row id and email address.Besides, since the id...

Verifying password_hash() in PDO prepared statements

php,mysql,pdo,prepared-statement
I'm trying to use the bcrypt algorithm for hashing the passwords but I've ran into a couple of problems. First of all, I can't find the appropriate spot to check whether password_verify() returns true. $admin = $_POST['admin-user']; $pass = $_POST['admin-pass']; $password_hash = password_hash($pass, PASSWORD_BCRYPT); if (isset($admin)&&isset($pass)&&!empty($admin)&&!empty($pass)) { $admin_select = $link->prepare("SELECT...

Is it necessary to Initialize a statement using MySQLi and PHP Prepared Statements

php,mysqli,prepared-statement
I have seen some tutorials on the web about using PHP Prepared Statements and MySQLi. some are using the mysqli_stmt mysqli::stmt_init() like: $stmt = $mysqli->stmt_init(); to call prepare() and other properties and methods of prepared statement and some are not initilaizing like if ($stmt = $mysqli->prepare("INSERT INTO CodeCall (FirstName, LastName)...

JDBC Return generated key or existing key

java,mysql,jdbc,prepared-statement
I have a table with unique index to eliminate duplicates (simplified example) CREATE TABLE `domain` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `subdomain` VARCHAR(255) NOT NULL, `domain` VARCHAR(63) NOT NULL, `zone` VARCHAR(63) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `UNIQUE` (`subdomain` ASC, `domain` ASC, `zone` ASC), ENGINE = InnoDB; I...

Correct PDO Syntax for Updating an Array of primary keys.

php,arrays,ajax,pdo,prepared-statement
Hi_I’m trying to run a PDO Update on my database whenever a certain event in my Facebook Canvas game occurs, but I’ve run into some difficulty with my syntax, I hope someone here can help. I have a table named Balance. This table contains the following columns: facebookID, goldbalance and...

Using sqlite3_bind_XXX inside a loop

c++,sqlite,prepared-statement
I want to do multiple parameterized inserts with SQLite in my code. For this : I have a single prepare statement outside of my loop as : error = sqlite3_prepare(connection, insert_sql, strlen(insert_sql), &stmt, NULL); I want inserts within a loop as: while ( not reached end of datafile ) {...

How do I pass a variable into a prepared statement in Ruby?

ruby,sqlite,prepared-statement
I have a method in Ruby to query a database and print out some data, and I'm trying to use a prepared statement instead. Here's the functioning method without the prepared statement: def print_state_speakers(*states) puts "STATE SPEAKERS" state_string = "'#{states.*"', '"}'" state_speakers = $db.execute(" SELECT name, location FROM congress_members WHERE...

Search barre php+mysql “Page not found”

php,mysql,search,prepared-statement
I've a small issue with this search barre : When I search for the Author or the Session, the search is succesful and everything is fine. But if I search anything in the last box (the Name one) my page is redirected to the site homepage. (with "Page not found"...

PDO prepared statement returning false

php,pdo,prepared-statement
Any idea why this is returning false? Code using to call function: $product = new Product; $allProducts = $product->getProducts(12); Function I'm calling: public function getProducts($limit) { $values = array($limit); $statement = $this->conn->prepare('SELECT * FROM sellify_items ORDER BY id DESC LIMIT ?'); $statement->execute($values); $result = $statement->fetchAll(); if ($result) { return $result;...

PreparedStatement throws syntax error [duplicate]

java,mysql,jdbc,prepared-statement
This question already has an answer here: Java PreparedStatement ResultSet TableModel MySQL Select Error 1 answer Im preparing a query using PreparedStatements and it runs fine when i hardcode te query with the condition parameter. but throws error , if the parameter is passed from setString() method. [email protected]: select...

how to output result outside while loop

php,mysql,while-loop,prepared-statement
When i echo the ouput inside the while loop, it gives me all the result i am expecting. When i echo outside, however, i only get one. I know if i use an array it will give me the result i am expecting, but don't know how. For some unknown...

Using prepared statement in Rails to insert multiple rows

ruby-on-rails,postgresql,prepared-statement
I am currently working on RoR with PostgreSQL. Basically, ActiveRecord satisfies most of the requirement of data retrieval. However, in some cases, it seems that using one statement would be much more efficient. Therefore, is it possible to use one prepared statement to do multiple insert as the followings? Or...

PDO statement error #1064

mysql,pdo,prepared-statement
I am trying to move from PDO quote et PDO prepare and execute, my query is like: $sql = 'SELECT * FROM nav_top1 WHERE id_top = (SELECT top_fr FROM nav_top WHERE top_fr = :rub ORDER BY top1_order ASC'; echo $sql.'<br>'; $query = $connexion->prepare($sql); $query->bindParam(':rub', $rub, PDO::PARAM_INT); $query->execute(); $list = $query->fetchAll();...

SQL Not Exists query

sql,sql-server,prepared-statement
I have problem integrating NOT EXISTS in my sql query. Let me explain the problem in detail I have four tables : branch_details , transactions,branch_order_relation and branch_pincode_relation. Here is my SQL query private static final String SELECT_ORDERS_BY_BRANCH = "select transaction_id,source_id,destination_id from transactions,branch_pincode_relation,branch_details,branch_order_relation where branch_details.branch_email = ? and branch_details.branch_id = branch_pincode_relation.branch_id...

In prepared statement is setString() the only useful method to prevent SQL injection?

java,jdbc,prepared-statement,sql-injection
What's the need to use: pstatement.setInt(); pstatements.setFloat(); etc. and all these methods other than setString() which is the only method useful to prevent SQL injection?...

How Can I Assign the Results from Object Oriented Mysqli Prepared Statements

php,mysqli,prepared-statement
I am trying to assign the results from a mysqli prepared statement query, but I am having trouble assigning the results to my variables. I have tried several methods, and have confirmed that my query is running and returing data. Here is how I am trying to assign the results:...

undefined function mysqli_stmt_init() php error

php,mysqli,prepared-statement
I'm new to using php mysqli prepared statements. No matter what I try I always get this error message. Fatal error: Call to undefined function mysqli_stmt_init() in...(etc) I have close my database link further below in my code, it isn't show here. Here is my code: $link = mysqli_connect($mysql_host, $mysql_user,...

Alternative to ResultSet for storing data from database

java,sql,jdbc,prepared-statement,resultset
I have a database and at present I am using the PreparedStatement to call data from the database using an SQL statement. However I know that once a PreparedStatement has finished the ResultSet closes. I need an alternative to this (the resultset closing) as the Prepared Statement is run every...

How do i return an error statement if the query is empty?

prepared-statement
I would like echo something if the query is empty. session_start(); include 'inc/db.php'; $student_id = $_POST['username']; $password = $_POST['password']; if($stmt = $conn->prepare("SELECT p.parent_id, ps.student_id, p.password FROM parent p, parentstudent ps WHERE p.parent_id = ps.parent_id AND student_id = ? limit 1")) { $stmt->bind_param("s", $student_id); $stmt->execute(); $stmt->bind_result($id, $student_id, $bindpassword); while ($stmt->fetch()) {...

Password_verify bcrypt not working

php,passwords,prepared-statement
Thanks for helping me on this question. I am trying to compare the passwords with php password_verify but it is not working. Is there something wrong with my code? (i get the second message 'INVALID USER OR PASSWORD') Cheers! function login_aut($uname, $pass){ include('_con.php'); include('password.php'); $stmt = $conex->prepare("SELECT id, pass FROM...

Java SQL update syntax error

java,mysql,sql,prepared-statement
I have a function "update" on my server and I call it through "btnUpdateActionPerformed" on my client. I'm performing an update on two tables, namely "patient" and "insurance" but when I run it, the following error is displayed on server side: Error1: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL...

Where should ? be placed in a PreparedStatement? [duplicate]

java,mysql,sql,jdbc,prepared-statement
This question already has an answer here: Having a Column name as Input Parameter of a PreparedStatement 1 answer I am using PreparedStatement to select records from a table: public static String getMemberInfo(String columnName, Integer memberId) { String memberInfo = ""; String sql = "SELECT ? FROM member WHERE...

Wheres my Mistake?

java,database,prepared-statement,primary-key,sqlexception
I want to get the actual created Primary Key. I need it instantly for another Method but it returns an error. But it returns a SQLE. Ive no idea wheres my Mistake. I hope i gave you enaugh information. (The System.out.println(id) is just for me to check if it returns...

PDO Prepared Statements: Replacing the value of a column

php,sql,pdo,prepared-statement
How do you use prepared statements and bound parameters to replace a value in a column? For example, $stmt = "UPDATE users SET name = :name WHERE name = :name"; $stmt->bindParam(:name, $oldName); $stmt->bindParam(:name, $newName); $stmt->execute(); ...

Prepared statement not running MYSQLI PHP

php,mysqli,prepared-statement
I have been attempting to switch over to prepared statements, however I cant figure out why my new code no longer functions. I am new to using these and still learning but i understand it is the best practice for security. any help would be appreciated. Thank You. <?php $servername...

Error in php sql statement ($stmt2 is returning false but I dont know why)

sql,prepared-statement,sql-insert,bindparam
I am getting this error (Call to a member function bind_param() on a non-object ) for my prepared statement as below which I know means that there is some error in the sql statement but I cannot see any error at all. I have been staring at this for a...

PostgreSQL JDBC PreparedStatement's setBytes changes parameter value

java,postgresql,jdbc,prepared-statement
I have PostgreSQL table that contains a bytea column. For example: CREATE TABLE my_table ( text_col text NOT NULL, bytea_col bytea NOT NULL ); The insert into the table uses a PreparedStatement something like this: ... byte[] value = "ABC".getBytes(); String insertStmt = "INSERT INTO my_table (text_col, bytea_col) VALUES (?,...

SQL Statement and Prepared Statement error

java,mysql,sql,prepared-statement,inner-join
The user inputs a disease and the SQL is supposed to return all patient details who have the disease. But i'm getting the following error: 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...

Update table field add by 1 every update using prepared statement in PHP

php,sql-update,prepared-statement
Here is the sample code but not working. if($increment = $cxn -> prepare("UPDATE products SET `yes`=? WHERE `id`=?")) { $yes = 'yes + 1'; $increment -> bind_param("is", $yes, $id); $increment -> execute(); $increment -> close(); }else{ die(mysqli_error($cxn)); } Data type: $yes -> integer $id -> string Problem: It did not...

Dynamic prepared statement, PHP

php,mysql,prepared-statement
I've checked almost all questions that produce the same error but all of these questions bind parameters in some wrong way. Perhaps and most probably I too am binding params incorrectly though my case is different because I've dynamic query. I am creating query dynamically from input which is being...

Using MySQLi prepared statements in PHP, getting “No data supplied for parameters in prepared statement ”

php,mysql,mysqli,runtime-error,prepared-statement
I'm trying to update my site to use prepared statements, but I keep getting this error and I cannot seem to figure out why. I've been searching Google and Stackoverflow for a week, trying everything I've found but nothing has fixed the issue. I'm sure I'm just misunderstanding something somewhere....

SELECT within SELECT PDO prepared statement [duplicate]

php,mysql,security,pdo,prepared-statement
This question already has an answer here: Are PDO prepared statements sufficient to prevent SQL injection? 7 answers I'm thinking of an example like this one: The request hits a page at an url (by whichever means), with a parameter. example.com/api/page?name=bob. It's my understanding that you should do a...

Inserting data while iterating over a result set using prepared statments [closed]

php,mysqli,prepared-statement
I'm starting to use the MySQL prepare and I have a problem. How do SELECT and INSERT then? $mysqli = new mysqli("localhost","root","pass","db"); $query = $mysqli->prepare("SELECT url FROM servers"); $query->execute(); $query->bind_result($data); $query2 = $mysqli->prepare("INSERT INTO links(url) VALUES (?)"); $query2->bind_param("s", $data); while ($query->fetch()) { echo $data; $query2->execute(); $query2->close(); } $query->close(); I tested...

How to accept apostrophe in a form field for MySQL

mysql,php,prepared-statement
I have a form that accepts a few names and phone numbers and posts them to a PHP script which then inserts those values into a MySQL table. The code (PHP) is pretty straightforward as you can see here: $sql = "INSERT INTO Contact_table (PHONE, NAME) VALUES "; for ($i...

How can I use DECLARE clause in a statement on jdbc?

java,mysql,jdbc,prepared-statement,sql-insert
I am currently trying to use a DECLARE clause in a preparedStatent with jdbc. The code that I wrote is: statement.executeUpdate(" declare @variable int set @variable = "+timer+" INSERT INTO table1 values (ip, protocol, counter, timer) SELECT ip,protocol,counter,@variable FROM table2 ORDER BY counter DESC LIMIT 5 OFFSET 0 ;"); What...

MySql prepared statement is not working for SELECT,but works for all other statement

php,mysql,prepared-statement,parameterized-query
I have found same question at SO Prepared statement works for INSERT but not for SELECT and tried to follow it,but no luck.One more thing, that question is on OOP structure,but my one is procedural style Here is my code $stmt = mysqli_stmt_init($connect_dude); if(mysqli_stmt_prepare($stmt,"SELECT headx FROM main_page WHERE user_id=?")){ mysqli_stmt_bind_param($stmt,...

MySQL: Get rows with creation date string newer than given date string

mysql,prepared-statement,string-comparison
I am trying to create a prepared statement with following code: $statement = $db->prepare("SELECT * FROM myTable WHERE STR_CMP(creationDate, $startingDate) = 1 ORDER BY creationDate DESC "); I have also tried this: $statement = $db->prepare("SELECT * FROM myTable WHERE (creationDate > $startingDate) = 1 ORDER BY creationDate DESC "); But...

Values Not Being Inserted with prepareStatement in Derby Database

java,prepared-statement,derby
I've created a very simple table, and am attempting to insert into it. The table exists, but nothing I try to insert sticks; the resultSet is always null. I think I'm auto-incrementing my primary key correctly. Any ideas? Thank you! String createGenreTableSQL = "CREATE TABLE Genre (GenreID INTEGER NOT NULL...

Php fails to build an array with character ö

php,mysqli,prepared-statement,special-characters
From what I can tell, PHP fails on building array with special character. Not sure where or why this is happening and how to solve. function findRelated($subpass){ $subpass = "$subpass%"; global $mysqli; if($stmt = $mysqli->prepare("SELECT pass FROM `passwords` WHERE pass LIKE ? LIMIT 500")) { $stmt->bind_param('s', $subpass); if(!$stmt->execute()) { $stmt->close();...

rename table prepared statement

mysql,sql,stored-procedures,prepared-statement
I'm attempting to write a stored procedure in MySQL that removes and renames tables based on a specified prefix (in this case 'migrate_'). The code should recursively rename all tables starting with 'migrate_' until none remain, however, I'm getting an error when trying to run it. BEGIN SELECT COUNT(*) INTO...

Using Timestamp in java sql prepared statement

java,mysql,sql-server,prepared-statement,sql-timestamp
I am trying to execute a select query using prepared statement in Java. In Where clause im checking for a condition on Timestamp type column as shown below. String selectSQL = "select * from db.keycontacts WHERE CREATEDDATETIME>?"; PreparedStatement preparedStatement = connect.prepareStatement(selectSQL); preparedStatement.setTimestamp(1, convertStrToTimestamp(lastSyncTimeStamp)); resultSet = preparedStatement.executeQuery(selectSQL ); //function to convert...

Getting error when using prepareStatement with interval in query

java,oracle,prepared-statement,intervals
When running this query SELECT SYSDATE + INTERVAL '7' DAY FROM DUAL; in a prepareStatement like this PreparedStatement ps = connection.prepareStatement("select sysdate + interval ? day from dual" ); ps.setString(1, "7"); ps.executeQuery(); It will throw an exception, that the syntax is not good, it clearly is, cuz i'm able to...

SQL injection and prepared statement, when does it get overkill?

php,mysqli,prepared-statement,sql-injection
I've read alot about sql injection and i've been using mysqli prepared statement for over a year now. The closer i got to my question was this one Why does this MySQLI prepared statement allow SQL injection? Now, i want to create a function to run a query based on...

JDBC preparedStatement not working in JSP

jsp,jdbc,oracle11g,prepared-statement
PreparedStatement is working fine if query is static (no parameters), for example: select * from RWEMP; but if I use the code below with a search condition: SELECT * FROM RWEMP WHERE ENAME= ? It doesn't show anything, it is just showing the table headers. <FORM METHOD="get"> <INPUT TYPE="text"...

conditional .set method for preparedstatement recursively

java,recursion,prepared-statement
i have a list of columns to check for null and insert them to db. i know it is simple if/else. if (lvl1.equalsIgnoreCase("NULL")) { stmt.setNull(2, java.sql.Types.INTEGER); } else { stmt.setString(2, lvl1); } but for at least 10 columns to write this, i hope there is more easier simpler one-line code...

How prepared statement protect again SQL injection in below statement

php,pdo,prepared-statement
I have gone through various document (SO post as well) about how exactly Prepared statement of PDO protect user from SQL injection. Although,I understand it protect user because in prepared statement,user record is directly not executing on server insted we are sending positional / named parameter ( ? / :name)...

How do I select every row from a table based on a string containing the name of the table?

mysql,sql,prepared-statement,dynamic-sql
In MySQL, I have a number of procedures which are more or less identical - they all perform the same (or very similar) operations, but they perform it on different tables. I'd like to reduce these to one procedure, parameterized by table name, if possible. For example, suppose I wanted...

Migrating to prepared statements

php,prepared-statement,fetch
I know that there are similar topics to this but they didn't helped me out, I want to migrate my code to prepared statements but I keep on getting errors or wrong answers. The plan is to get code like this: $sql = "SELECT * FROM our_videos ORDER BY datemade...

Prepared Statement not working- Blank page

php,mysql,prepared-statement
I have this code $con = new mysqli('####', '####', '####', '####'); if(mysqli_connect_errno()){ echo 'Connection Failed:' . mysqli_connect_errno(); exit(); } //Variables $user = $_POST['username']; $zone = $_POST['password']; $pass = strtoupper(hash("whirlpool", $zone)); //Prepare if($stmt = $con -> prepare("SELECT * FROM `accounts` WHERE Username=? AND Key=?")){ $stmt -> bind_param("ss", $user, $pass); $stmt ->...

How add a value from select/dropdown list to my Prepare Statement?

php,sql,pdo,prepared-statement
First question here but I have been teaching myself PDO over the past few days to integrate into a site I'm developing and I'm not quite sure what I'm doing wrong. I have been trying to use GET to retrieve the selection from a dropdown menu in order to limit...

Java JDBC PreparedStatement Foreign Key Constraint Failed

java,sqlite,jdbc,prepared-statement
I'm designing a billing program with SQLite and JDBC, and I'm trying to use this helper method: public static void preparedInsert(String query, String[] inserters) { Connection c = connect(); try { PreparedStatement statement = c.prepareStatement(query); for (int i = 0; i < inserters.length; i++) { statement.setObject(i + 1, "\'" +...

How to use prepared statement efficiently using datastax java driver in Cassandra?

java,cassandra,prepared-statement,datastax-java-driver
I need to query one of the tables in Cassandra using Datastax Java driver. Below is the code I have which works fine - public class TestCassandra { private Session session = null; private Cluster cluster = null; private static class ConnectionHolder { static final TestCassandra connection = new TestCassandra();...

Sequence.NEXTVAL in Oracle 12c with rs.getInt() or getLong() fails - so what datatype it returns?

java,oracle,jdbc,prepared-statement,sequence
I am fetching next value of sequence with the ps = connection.prepareStatement("select seq.nextval from dual"); But neither getLong() nor getInt() works. So how to correctly get the value from the ResultSet then? full code: public static long seqGetNextValue(String sequence) { Connection connection = Util.getConnection(); PreparedStatement ps = null; ResultSet rs...

invalid object or resource mysqli_stmt

php,mysql,mysqli,prepared-statement
I want to run multiple mysql queries( not concurrently). I am using prepared statements for doing so. This is a gist of my code : <?php if(isset($_GET['username'])&&isset($_GET['activationid'])){ require_once("../database/db_connect.php"); $stmt= $mysqli->stmt_init(); $stmt->prepare("Select username FROM users where username= ? AND activationid= ?"); $username=$_GET['username']; $activationid=$_GET['activationid']; $stmt->bind_param("ss",$username,$activationid); $stmt->execute();...

Insert Data in Oracle DB using PHP

php,oracle,prepared-statement,oci
Inserting data in oracle DB using oci_8. Sample query to insert string with special characters or quotes update TABLENAME set COMMENTS = 'As per Mark's email dated 28-Feb-2015 - Bill Gates & Team's effort' where ID = 99; To insert/update $query = 'update TABLENAME set COMMENTS = '$_POST[comments]'; $result =...