Search Results

Search found 7596 results on 304 pages for 'prepared statement'.

Page 2/304 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Unable to compare valuesfrom mysql in a prepared statement

    - by Cortopasta
    I can't seem to get this to connect to the database so that I can run my prepared statement. Does anybody have an idea what I've forgotten? private function check_credentials($plain_username, $password) { global $dbcon; $ac = new ac(); $ac->dbconnect(); $userid = $dbcon->prepare('SELECT id FROM users WHERE username = :username AND password = :password LIMIT 1'); $userid->bindParam(':username', $plain_username); $userid->bindParam(':password', $password); $userid->execute(); $id = $userid->fetch(); Return $id; } EDIT: I changed the SQL query from a SELECT FROM query, to an INSERT INTO query and it worked. WHat the heck is going on?

    Read the article

  • mysqli prepared statements select *

    - by Victor Dallecio
    I've spent this sunday trying to find what is wrong to the following code as it is not counting the rows. Could somebody help me with it? Thanks! /*check if same IP has visited today*/ if ($stmt = $mysqli->query('SELECT * FROM table WHERE colum1 = ? AND colum2 > DATE_SUB(NOW(), INTERVAL 1 DAY)')) { $stmt->bind_param('s', $ip); /* execute query */ $stmt->execute(); /*number of rows */ /*store result when using prepared statements*/ $stmt->store_result(); $row_cnt = $stmt->num_rows; printf("Result set has %d rows.\n", $row_cnt); $stmt->close(); }

    Read the article

  • Batch Inserts And Prepared Query Error

    - by ircmaxell
    Ok, so I need to populate a MS Access database table with results from a MySQL query. That's not hard at all. I've got the program written to where it copies a template .mdb file to a temp name and opens it via odbc. No problem so far. I've noticed that Access does not support batch inserting (VALUES (foo, bar), (second, query), (third query)). So that means I need to execute one query per row (there are potentially hundreds of thousands of rows). Initial performance tests show a rate of around 900 inserts/sec into Access. With our largest data sets, that could mean execution times of minutes (Which isn't the end of the world, but obviously the faster the better). So, I tried testing a prepared statement. But I keep getting an error (Warning: odbc_execute() [function.odbc-execute]: SQL error: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect , SQL state 07001 in SQLExecute in D:\....php on line 30). Here's the code I'm using (Line 30 is odbc_execute): $sql = 'INSERT INTO table ([field0], [field1], [field2], [field3], [field4], [field5]) VALUES (?, ?, ?, ?, ?, ?)'; $stmt = odbc_prepare($conn, $sql); for ($i = 200001; $i < 300001; $i++) { $a = array($i, "Field1 $", "Field2 $i", "Field3 $i", "Field4 $i", $i); odbc_execute($stmt, $a); } So my question is two fold. First, is there any idea on why I'm getting that error (I've checked, and the number in the array matches the field list which matches the number of parameter ? markers)? And second, should I even bother with this or just use the straight INSERT statements? Like I said, time isn't critical, but if it's possible, I'd like to get that time as low as possible (Then again, I may be limited by disk throughput, since 900 operations/sec is high already)... Thanks

    Read the article

  • Java Prepared Statement arguments!

    - by Epitaph
    I am planning to replace repeatedly executed Statement objects with PreparedStatement objects to improve performance. I am using arguments like the MySQL function now(), and string variables. Most of the PreparedStatement queries I have seen contained constant values (like 10, and strings like "New York") as arguments used for the "?" in the queries. How would I go about using functions like now(), and variables as arguments? Is it necessary to use the "?"s in the queries instead of actual values? I am quite confounded.

    Read the article

  • Java Prepared Statement Error

    - by Suresh S
    Hi Guys the following code throws me an error i have an insert statement created once and in the while loop i am dynamically setting parameter , and at the end i says ps2.addBatch() again while ( (eachLine = in.readLine()) != null)) { for (int k=stat; k <=45;k++) { ps2.setString (k,main[(k-2)]); } stat=45; for (int l=1;l<= 2; l++) { ps2.setString((stat+l),pdp[(l-1)]);// Exception } ps2.addBatch(); } This is the error java.lang.ArrayIndexOutOfBoundsException: 45 at oracle.jdbc.dbaccess.DBDataSetImpl._getDBItem(DBDataSetImpl.java:378) at oracle.jdbc.dbaccess.DBDataSetImpl._createOrGetDBItem(DBDataSetImpl.java:781) at oracle.jdbc.dbaccess.DBDataSetImpl.setBytesBindItem(DBDataSetImpl.java:2450) at oracle.jdbc.driver.OraclePreparedStatement.setItem(OraclePreparedStatement.java:1155) at oracle.jdbc.driver.OraclePreparedStatement.setString(OraclePreparedStatement.java:1572) at Processor.main(Processor.java:233)

    Read the article

  • Why is there never any controversy regarding the switch statement? [closed]

    - by Nick Rosencrantz
    We all know that the gotostatement should only be used on very rare occasions if at all. It has been discouraged to use the goto statement countless places countless times. But why it there never anything like that about the switch statement? I can understand the position that the switch statement should always be avoided since anything with switch can always be expressed by if...else... which is also more readable and the syntax of the switch statement if difficult to remember. Do you agree? What are the arguments in favor of keeping the 'switch` statement? It can also be difficult to use if what you're testing changes from say an integer to an object, then C++ or Java won't be able to perform the switch and neither C can perform switch on something like a struct or a union. And the technique of fall-through is so very rarely used that I wonder why it was never presented any regret of having switch at all? The only place I know where it is best practice is GUI code and even that switch is probably better coded in a more object-oriented way.

    Read the article

  • T-SQL (SCD) Slowly Changing Dimension Type 2 using a merge statement

    - by AtulThakor
    Working on stored procedure recently which loads records into a data warehouse I found that the existing record was being expired using an update statement followed by an insert to add the new active record. Playing around with the merge statement you can actually expire the current record and insert a new record within one clean statement. This is how the statement works, we do the normal merge statement to insert a record when there is no match, if we match the record we update the existing record by expiring it and deactivating. At the end of the merge statement we use the output statement to output the staging values for the update,  we wrap the whole merge statement within an insert statement and add new rows for the records which we inserted. I’ve added the full script at the bottom so you can paste it and play around.   1: INSERT INTO ExampleFactUpdate 2: (PolicyID, 3: Status) 4: SELECT -- these columns are returned from the output statement 5: PolicyID, 6: Status 7: FROM 8: ( 9: -- merge statement on unique id in this case Policy_ID 10: MERGE dbo.ExampleFactUpdate dp 11: USING dbo.ExampleStag s 12: ON dp.PolicyID = s.PolicyID 13: WHEN NOT MATCHED THEN -- when we cant match the record we insert a new record record and this is all that happens 14: INSERT (PolicyID,Status) 15: VALUES (s.PolicyID, s.Status) 16: WHEN MATCHED --if it already exists 17: AND ExpiryDate IS NULL -- and the Expiry Date is null 18: THEN 19: UPDATE 20: SET 21: dp.ExpiryDate = getdate(), --we set the expiry on the existing record 22: dp.Active = 0 -- and deactivate the existing record 23: OUTPUT $Action MergeAction, s.PolicyID, s.Status -- the output statement returns a merge action which can 24: ) MergeOutput -- be insert/update/delete, on our example where a record has been updated (or expired in our case 25: WHERE -- we'll filter using a where clause 26: MergeAction = 'Update'; -- here   Complete source for example 1: if OBJECT_ID('ExampleFactUpdate') > 0 2: drop table ExampleFactUpdate 3:  4: Create Table ExampleFactUpdate( 5: ID int identity(1,1), 3: go 6: PolicyID varchar(100), 7: Status varchar(100), 8: EffectiveDate datetime default getdate(), 9: ExpiryDate datetime, 10: Active bit default 1 11: ) 12:  13:  14: insert into ExampleFactUpdate( 15: PolicyID, 16: Status) 17: select 18: 1, 19: 'Live' 20:  21: /*Create Staging Table*/ 22: if OBJECT_ID('ExampleStag') > 0 23: drop table ExampleStag 24: go 25:  26: /*Create example fact table */ 27: Create Table ExampleStag( 28: PolicyID varchar(100), 29: Status varchar(100)) 30:  31: --add some data 32: insert into ExampleStag( 33: PolicyID, 34: Status) 35: select 36: 1, 37: 'Lapsed' 38: union all 39: select 40: 2, 41: 'Quote' 42:  43: select * 44: from ExampleFactUpdate 45:  46: select * 47: from ExampleStag 48:  49:  50: INSERT INTO ExampleFactUpdate 51: (PolicyID, 52: Status) 53: SELECT -- these columns are returned from the output statement 54: PolicyID, 55: Status 56: FROM 57: ( 58: -- merge statement on unique id in this case Policy_ID 59: MERGE dbo.ExampleFactUpdate dp 60: USING dbo.ExampleStag s 61: ON dp.PolicyID = s.PolicyID 62: WHEN NOT MATCHED THEN -- when we cant match the record we insert a new record record and this is all that happens 63: INSERT (PolicyID,Status) 64: VALUES (s.PolicyID, s.Status) 65: WHEN MATCHED --if it already exists 66: AND ExpiryDate IS NULL -- and the Expiry Date is null 67: THEN 68: UPDATE 69: SET 70: dp.ExpiryDate = getdate(), --we set the expiry on the existing record 71: dp.Active = 0 -- and deactivate the existing record 72: OUTPUT $Action MergeAction, s.PolicyID, s.Status -- the output statement returns a merge action which can 73: ) MergeOutput -- be insert/update/delete, on our example where a record has been updated (or expired in our case 74: WHERE -- we'll filter using a where clause 75: MergeAction = 'Update'; -- here 76:  77:  78: select * 79: from ExampleFactUpdate 80: 

    Read the article

  • Getting the record ID just added with mysql prepared statements

    - by dmontain
    I'm inserting a record using PDO (very similar to mysqli). $addRecord->execute(); To know if the operation worked, I've learned that I can save it to a variable $result that can be used as true false $result = $addRecord->execute(); if ($result){ //add successful } else { //add unsuccessful } What I'd like to do is also get the record id just added. In the table, each record has an auto_incremented field called id. I tried doing this $new_id = $result['id']; but it seems that $result is purely boolean and doesn't actually hold the actual record that was added. Can someone confirm this and how would I then access the record just added? Note that several people may be adding to the same table at the same time, so I think getting just the last one would not be very accurate.

    Read the article

  • Using wildcards in prepared statement - MySQLi

    - by Michael Irwin
    Hi! I'm trying to run the following query, and I'm having trouble with the wildcard. function getStudents() { global $db; $users = array(); $query = $db->prepare("SELECT id, adminRights FROM users WHERE classes LIKE ? && adminRights='student'"); $query->bind_param('s', '%' . $this->className . '%'); $query->execute(); $query->bind_result($uid, $adminRights); while ($query->fetch()) { if (isset($adminRights[$this->className]) && $adminRights[$this->className] == 'student') $users[] = $uid; } $query->close(); return $users; } I'm getting an error that states: Cannot pass parameter 2 by reference. The reason I need to use the wildcard is because the column's data contains serialized arrays. I guess, if there's an easier way to handle this, what could I do? Thanks in advance!

    Read the article

  • PDO prepared statement not working for login system

    - by Cortopasta
    Anybody no what I'm doing wrong here? I have a username and password hashed in my database, but i can't seem to get it to match the one I submit through the script. $res = $dbcon->prepare('SELECT id FROM users WHERE name = :name AND password = MD5(:password)'); $res->bindParam(':name', $user); $res->bindParam(':password', $password); $res->execute(); $row = $res->fetch(); for ($i=0; $i<7; $i++) { $row[$i]; }

    Read the article

  • Can't Insert Data Into Tables Containing Auto Increment Primary Key Using PHP Prepared Statements

    - by Drew
    I know I have that my connection to the database works, and a test I did using no auto-increment id worked fine for me. The code below refuses to work and I can't find a a way around it. My table has 3 columns, ID (auto increment), name and value. What do I need to change in order to get this to work? Thanks in advance //create placeholder query $query = "INSERT INTO prepared_test (name, value) VALUES (?,?)"; //prepare the query $stmt = mysqli_prepare($connection, $query); $name = 'steve'; $value = 45; mysqli_bind_param($stmt, array(MYSQLI_BIND_STRING, MYSQLI_BIND_INT), $name, $value); mysqli_execute($stmt); if(mysqli_stmt_affected_rows($stmt) != 1) die("issues"); mysqli_stmt_close($stmt); $connection-close();

    Read the article

  • 42000 Syntax error in query when executing prepared statement

    - by Griff McGriff
    I have been pulling my hair out trying to swap my current script over to PDO. I have simplified the MySQL query for this example, but the error remains even with this version. $sql = 'SELECT * FROM :table WHERE lastUpdate > :appDate'; try{ $db = connect(); $stmt = $db->prepare($sql); $stmt->bindParam(':table', $table); $stmt->bindParam(':appDate', $appDate); foreach($tablesToCheck as $table){ $stmt->execute(); $resultset[] = $stmt->fetchAll(); } } catch(PDOException $e){ print 'Error!: '.$e->getMessage().'<br/>'; }//End try catch $stmt-errorInfo() returns: ( [0] => 42000 [1] => 1064 [2] => 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 ''GroupName' WHERE lastUpdate > NULL' at line 1 )

    Read the article

  • How to use prepared statements (named parameters) on a php Class

    - by Mohamed Adib Errifai
    This is my first post here. I've searched in the site, but inforutunaly no matchs. Anyway, i want to know how to use named parameters on a class. so the pdo basic form is something like. $query = $bdd->prepare('SELECT * FROM table WHERE login = :login AND pww = :pww'); $query->execute(array('login' => $login, 'pww' => $pww)); and i want to integrate this on a class regardless of the number of parameters. Currently, i have this code http://pastebin.com/kKgSkaKt and for parameters, i use somethings like ( which is wrong and vulnerable to injection ) require_once 'classes/Mysql.class.php'; $mysql = new Mysql(); $sql = 'SELECT * FROM articles WHERE id = '.$_GET['id'].' LIMIT 1'; $data = $mysql->select($sql); And Thanks.

    Read the article

  • Need help fetching an array using prepared statments

    - by eldan221
    I have wrote the following code to fetch a string. But for some reason its only returning 1. I have doubled checked everything and it seems like its correct. I am not sure why its only returning 1? Any help here would be really appreciated! //Class Defined here function MenuCat($id){ $query = "SELECT menu_category_description FROM menu_categories WHERE id = ?"; $stmt = $this->db->prepare($query); $stmt->bind_param("i", $id); $stmt->execute(); $stmt->bind_result($menu_category_description); $row = $stmt->fetch(); return $row; } $display_category = $cat_des->MenuCat($id); echo $display_category

    Read the article

  • Prepared statement alternatives for this middle-man program?

    - by user2813274
    I have an program that is using a prepared statement to connect and write to a database working nicely, and now need to create a middle-man program to insert between this program and the database. This middle-man program will actually write to multiple databases and handle any errors and connection issues. I would like advice as to how to replicate the prepared statements such as to create minimal impact to the existing program, however I am not sure where to start. I have thought about creating a "SQL statement class" that mimics the prepared statement, only that seems silly. The existing program is in Java, although it's going to be networked anyways so I would be open to writing it in just about anything that would make sense. The databases are currently MySQL, although I would like to be open to changing the database type in the future. My main question is what should the interface for this program look like, and does doing this even make sense? A distributed DB would be the ideal solution, but they seem overly complex and expensive for my needs. I am hoping to replicate the main functionality of a distributed DB via this middle-man. I am not too familiar with sql-based servers distributing data (or database in general...) - perhaps I am fighting an uphill battle by trying to solve it via programming, but I would like to make an attempt at least.

    Read the article

  • CASE statement within WHERE statement

    - by niao
    Greetings, I would like to include CASE Statement inside my where statement as follows: SELECT a1.ROWGUID FROM Table1 a1 INNER JOIN Table2 a2 on a1.ROWGUID=a2.Table1ROWGUID WHERE a1.Title='title' AND (CASE WHEN @variable is not null THEN a1.ROWGUID in (SELECT * FROM #TempTable)) However, this 'CASE' statement does not work inside 'WHERE' statement. How can I do it correct?

    Read the article

  • Preparing a MySQL INSERT/UPDATE statement with DEFAULT values

    - by Raveren
    Quoting MySQL INSERT manual - same goes for UPDATE: Use the keyword DEFAULT to set a column explicitly to its default value. This makes it easier to write INSERT statements that assign values to all but a few columns, because it enables you to avoid writing an incomplete VALUES list that does not include a value for each column in the table. Otherwise, you would have to write out the list of column names corresponding to each value in the VALUES list. So in short if I write INSERT INTO table1 (column1,column2) values ('value1',DEFAULT); A new row with column2 set as its default value - whatever it may be - is inserted. However if I prepare and execute a statement in PHP: $statement = $pdoObject-> prepare("INSERT INTO table1 (column1,column2) values (?,?)"); $statement->execute(array('value1','DEFAULT')); The new row will contain 'DEFAULT' as its text value - if the column is able to store text values. Now I have written an abstraction layer to PDO (I needed it) and to get around this issue am considering to introduce a const DEFAULT_VALUE = "randomstring"; So I could execute statements like this: $statement->execute(array('value1',mysql::DEFAULT_VALUE)); And then in method that does the binding I'd go through values that are sent to be bound and if some are equal to self::DEFAULT_VALUE, act accordingly. I'm pretty sure there's a better way to do this. Has someone else encountered similar situations?

    Read the article

  • Question about DBD::CSB Statement-Functions

    - by sid_com
    From the SQL::Statement::Functions documentation: Function syntax When using SQL::Statement/SQL::Parser directly to parse SQL, functions (either built-in or user-defined) may occur anywhere in a SQL statement that values, column names, table names, or predicates may occur. When using the modules through a DBD or in any other context in which the SQL is both parsed and executed, functions can occur in the same places except that they can not occur in the column selection clause of a SELECT statement that contains a FROM clause. # valid for both parsing and executing SELECT MyFunc(args); SELECT * FROM MyFunc(args); SELECT * FROM x WHERE MyFuncs(args); SELECT * FROM x WHERE y < MyFuncs(args); # valid only for parsing (won't work from a DBD) SELECT MyFunc(args) FROM x WHERE y; Reading this I would expect that the first SELECT-statement of my example shouldn't work and the second should but it is quite the contrary. #!/usr/bin/env perl use warnings; use strict; use 5.010; use DBI; open my $fh, '>', 'test.csv' or die $!; say $fh "id,name"; say $fh "1,Brown"; say $fh "2,Smith"; say $fh "7,Smith"; say $fh "8,Green"; close $fh; my $dbh = DBI->connect ( 'dbi:CSV:', undef, undef, { RaiseError => 1, f_ext => '.csv', }); my $table = 'test'; say "\nSELECT 1"; my $sth = $dbh->prepare ( "SELECT MAX( id ) FROM $table WHERE name LIKE 'Smith'" ); $sth->execute (); $sth->dump_results(); say "\nSELECT 2"; $sth = $dbh->prepare ( "SELECT * FROM $table WHERE id = MAX( id )" ); $sth->execute (); $sth->dump_results(); outputs: SELECT 1 '7' 1 rows SELECT 2 Unknown function 'MAX' at /usr/lib/perl5/site_perl/5.10.0/SQL/Parser.pm line 2893. DBD::CSV::db prepare failed: Unknown function 'MAX' at /usr/lib/perl5/site_perl/5.10.0/SQL/Parser.pm line 2894. [for Statement "SELECT * FROM test WHERE id = MAX( id )"] at ./so_3.pl line 30. DBD::CSV::db prepare failed: Unknown function 'MAX' at /usr/lib/perl5/site_perl/5.10.0/SQL/Parser.pm line 2894. [for Statement "SELECT * FROM test WHERE id = MAX( id )"] at ./so_3.pl line 30. Could someone explaine me this behavior?

    Read the article

  • Return number of rows affected by SQL UPDATE statement in Java

    - by Krt_Malta
    I'm using a MySQL database and accessing it through Java. PreparedStatement prep1 = this.connection.prepareStatement("UPDATE user_table SET Level = 'Super' WHERE Username = ?"); prep1.setString(1, username); The update statement above works fine however I'd like to get the number of rows affected with this statement. Is this possible please?

    Read the article

  • Why does Clang/LLVM warn me about using default in a switch statement where all enumerated cases are covered?

    - by Thomas Catterall
    Consider the following enum and switch statement: typedef enum { MaskValueUno, MaskValueDos } testingMask; void myFunction(testingMask theMask) { switch theMask { case MaskValueUno: {}// deal with it case MaskValueDos: {}// deal with it default: {} //deal with an unexpected or uninitialized value } }; I'm an Objective-C programmer, but I've written this in pure C for a wider audience. Clang/LLVM 4.1 with -Weverything warns me at the default line: Default label in switch which covers all enumeration values Now, I can sort of see why this is there: in a perfect world, the only values entering in the argument theMask would be in the enum, so no default is necessary. But what if some hack comes along and throws an uninitialized int into my beautiful function? My function will be provided as a drop in library, and I have no control over what could go in there. Using default is a very neat way of handling this. Why do the LLVM gods deem this behaviour unworthy of their infernal device? Should I be preceding this by an if statement to check the argument?

    Read the article

  • How is a switch statement better than a series of if statements? [closed]

    - by user1276078
    Possible Duplicate: Should I use switch statements or long if…else chains? I'm working on a small program that will conduct an Insertion Sort. A number will be inputted through the keyboard and stored in a variable I called "num." I've decided to use a switch statement in order to obtain the number inputted. switch( e.getKeyCode() ) { case KeyEvent.VK_0: num = 0; break; case KeyEvent.VK_1: num = 1; break; case KeyEvent.VK_2: num = 2; break; case KeyEvent.VK_3: num = 3; break; case KeyEvent.VK_4: num = 4; break; case KeyEvent.VK_5: num = 5; break; case KeyEvent.VK_6: num = 6; break; case KeyEvent.VK_7: num = 7; break; case KeyEvent.VK_8: num = 8; break; case KeyEvent.VK_9: num = 9; break; } I realized one other course of action could have been to use a set of if statements. if( e.getKeyCode() == KeyEvent.VK_0 ) num = 0; else if( e.getKeyCode() == KeyEvent.VK_1 ) num = 1; etc. for every number up until 9. I then wondered what the essential difference is between a switch statement and a series of if statements. I know it saves space and time to write, but it's not that much. So, my question is, aside from the space, does a switch statement differ from a series of if statments in any way? Is it faster, less error-prone, etc.? This question really doesn't affect my code that much. I was just wondering. Also, this question pertains to the JAVA language, not any other programming language.

    Read the article

  • Search select statement

    - by Nana
    I am creating a page which would have different field for the user to search from. e.g. search by: Grade: -dropdownlist1- Student name: -dropdownlist2- Student ID: -dropdownlist3- Lessons: -dropdownlist4- Year: -dropdownlist5- How do I write the select statement for this? Each dropdownlist would need a select statement which would extract out different data from the database. But, I want to write ONE select statement which can dynamically choose the dropdownlist options. Instead of writing many many select statement. Lets say; Grade: -dropdownlist1- ; default value(all) Student name: -dropdownlist2-; default value(all) Student ID: -dropdownlist3-; 0-100 is choosen Lessons: -dropdownlist4-; A-C is choosen Year: -dropdownlist5-; 2009 is choosen

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >