PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in - pdo

i made this code:
class Consultas{
public function insertarUsuario($arg_nombre, $arg_usuario, $arg_passwd){
$modelo = new Conexion();
$conexion = $modelo->get_conexion();
$sql = "insert into tablausuarios (nombre, usuario,password) values(:nombre, :usu, :passw)";
$statement = $conexion->prepare($sql);
$statement->bindParam(':nombre', $arg_nombre);
$statement->bindParam(':usuario', $arg_usuario);
$statement->bindParam(':password', $arg_passwd);
if($statement->execute(array(":nombre"=>$arg_nombre, ":usuario"=>$arg_usuario, ":password"=>$arg_passwd))){
return "Registro creado satisfactoriamente";
}else{
return "error al crear registro";
}
}
and have this error: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in
can someone help me please?

You are repeating the bind param thing. and your parameter isn't the same on your execute method. I've updated code for you try with it.
Update this code to like this:
class Consultas{
public function insertarUsuario($arg_nombre, $arg_usuario, $arg_passwd){
$modelo = new Conexion();
$conexion = $modelo->get_conexion();
$sql = "insert into tablausuarios (nombre, usuario,password) values(:nombre, :usu, :passw)";
$statement = $conexion->prepare($sql);
if($statement->execute(array(":nombre"=>$arg_nombre, ":usu"=>$arg_usuario, ":passw"=>$arg_passwd))){
return "Registro creado satisfactoriamente";
}else{
return "error al crear registro";
}
}
Hope this will help you :)

class Consultas{
public function insertarUsuario($arg_nombre, $arg_usuario, $arg_passwd){
$modelo = new Conexion();
$conexion = $modelo->get_conexion();
$statement = $conexion->prepare("insert into tablausuarios (nombre, usuario,password) values (?,?,?)");
if($statement->execute(array($arg_nombre,$arg_usuario,$arg_passwd))){
return "Registro creado satisfactoriamente";
}else{
return "error al crear registro";
}
}
try this suggestion i think that it help you

Related

Inserting data through GUI into sql server

I'm able to execute sql statements by writing the sql codes (Insert etc) on Eclipse and it is being displayed into sql server correctly. Connection has been done. But what should I do when a user wants to add data through a GUI interface (text field) and the data need to get stored into the database automatically ??
my code in the ADD button, but i'm getting the Error: java.lang.NullPointerException ! Help please..
try {
String pid = ProductID.getText();
String sql = "insert into Products_tbl values (' " +pid + " ')";
// Running the sql query
rs = st.executeQuery(sql);
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "Welcome");
}
else if (count > 1) {
JOptionPane.showMessageDialog(null,"Duplicate User Access Denied");
}
else {
JOptionPane.showMessageDialog(null, " User Not Found ");
}
}
catch (Exception ex) {
System.out.println("Error: " + ex);
}
1- Using (' " +pid + " ')" is not safe because SQL injection may occur. Use SqlParameters instead. Please check:
https://www.w3schools.com/sql/sql_injection.asp
2- I am pretty sure something is wrong with the line: rs = st.executeQuery(sql);
Here, I bet the value of st is null. Make sure that your connection variable is defined and set correctly and you created the statement like below:
st = connection.createStatement();
You can also try executeupdate(query) instead of executequery(query) like:
int flag = st.executeUpdate(query);
Ref: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29
3- Please use printStackTrace() method while printing the error in the catch blog, the error message would be more understandable.
System.out.println("Error: " + ex.printStackTrace());

Phalcon: specific column on joined PHQL

The below PHQL generates a complex resultset like it should:
$phql = "SELECT User.*, ProductUser.* "
. "FROM ProductUser "
. "INNER JOIN User "
. "WHERE ProductUser.product_id = 5";
Replacing ProductUser.* with an existing column like ProductUser.id causes an error:
MESSAGE: The index does not exist in the row
FILE: phalcon/mvc/model/row.zep
LINE: 67
This is version 2.0.6. Is this a bug or am I making a mistake somewhere? According to the documentation it should be fine.
It was my mistake (expecting the row to always be an object).
I hope this helps someone because looping complex resultsets is not in the documentation.
$result = $this->modelsManager->createQuery($phql)->execute();
if ($result instanceof \Phalcon\Mvc\Model\Resultset\Complex) {
foreach ($result as $rows) {
foreach ($rows as $row) {
if (is_object($row)) {
$modelData = $row->toArray());
// this is what I needed
} else {
$id = $row;
}
}
}
}
First of all you're missing the ON clause in your query.
Anyways, it's easier and more error prone to use Phalcon's query builder for querying:
<?php
// modelManager is avaiable in the default DI
$queryBuilder = $this->modelsManager->createBuilder();
$queryBuilder->from(["product" => 'Path\To\ProductUser']);
// Inner join params are: the model class path, the condition for the 'ON' clause, and optionally an alias for the table
$queryBuilder->innerJoin('Path\To\User', "product.user_id = user.id", "user");
$queryBuilder->columns([
"product.*",
"user.*"
]);
$queryBuilder->where("product.id = 5");
// You can use this line to debug what was generated
// $generatedQuery = $queryBuilder->getPhql();
// var_dump($generatedQuery);
// Finish the query building
$query = $queryBuilder->getQuery();
// Execute it and get the results
$result = $query->execute();
// Now use var_dump to see how the result was fetched
var_dump($result);
exit;

Excel QueryTable Parameters do not bind Sql Parameters

I'm new in Excel development and I have an issue that It's driving me crazy. I hope you can help me.
Let me explain the situation,
I'm trying to create a QueryTable to import data from SQL , but ... I get an error at the moment to refresh the QueryTable,
the error message indicates that I'm not passing values for required parameters. ( It works hard coded :[ )
After many hours of investigation, I wasn't able to find a solution or an example to guide me... And here I am :|
I don't know what I'm doing wrong, Here is some code
foreach (Range row in main.Rows)
{
//row.Clear();
rowID = row.Row;
if (string.IsNullOrEmpty(getAccounts(rowID, columnID)) )
continue;
/* string connectionString = // \"
string.Format("OLEDB;Provider=SQLOLEDB;Data Source={0};Initial Catalog={1};User ID={2};Password={3}",
*/
//string sql = "EXECUTE [Funciones].[Cuenta_Saldo_Anho] ?,?";
//if (!string.IsNullOrEmpty(txtTipoSaldo.Text)) sql += ",?";
string sql = "{CALL [Funciones].[Cuenta_Saldo_Anho] (?, ?";
sql += (!string.IsNullOrEmpty(txtTipoSaldo.Text))? "" : ", ?" + ")}"; // optional parameter
var qt = wSheet.QueryTables.Add( connectionString, row.Cells , sql);
qt.CommandType = XlCmdType.xlCmdSql;
var ctas = qt.Parameters.Add("#ctas", XlParameterDataType.xlParamTypeLongVarChar);
//ctas.SetParam(XlParameterType.xlConstant, cuentas);
ctas.SetParam(XlParameterType.xlRange, wSheet.Cells[rowID, columnID]));
ctas.RefreshOnChange = true;
qt.Parameters.Add("#anho", XlParameterDataType.xlParamTypeInteger)
.SetParam(XlParameterType.xlConstant, Int32.Parse(anho));
qt.Parameters.Add("#tipoSaldo", XlParameterDataType.xlParamTypeVarChar)
.SetParam(XlParameterType.xlConstant, txtTipoSaldo.Text);
//qt.BackgroundQuery = true;
qt.FieldNames = false;
qt.AdjustColumnWidth = false;
qt.RefreshOnFileOpen = false;
qt.Refresh();
}
Any help is welcome. Thanks.

my query take a long time to run ,why?

I have a query that returns c.a 1800 records( not many) but It takes long time to ran (10 seconds) but I can not understand why?
this is my query that takes a long time:
SELECT tb_KonzeptFunktionen.Konzept AS KonzeptID, tb_KonzeptFunktionen.Funktion,
tb_KonzeptFunktionen.Version,
qryFunktionen_Übersicht.ID,
qryFunktionen_Übersicht.Fehlerpfad_Kommentar AS Kommentar,
qryFunktionen_Übersicht.Fehlerpfadname,
qryFunktionen_Übersicht.Fehlerpfad_CDT,
qryFunktionen_Übersicht.Fehlerpfad_Kommentar,
qryFunktionen_Übersicht.symptombasiert,
qryFunktionen_Übersicht.Beschreibung_vorhanden,
qryFunktionen_Übersicht.Max_Pfad,
qryFunktionen_Übersicht.Max_Info,
qryFunktionen_Übersicht.Max_Status,
qryFunktionen_Übersicht.Max_Strategie,
qryFunktionen_Übersicht.Max_Prüfplan,
qryFunktionen_Übersicht.Min_Pfad,
qryFunktionen_Übersicht.Min_Info,
qryFunktionen_Übersicht.Min_Status,
qryFunktionen_Übersicht.Min_Strategie,
qryFunktionen_Übersicht.Min_Prüfplan,
qryFunktionen_Übersicht.Sig_Pfad,
qryFunktionen_Übersicht.Sig_Info,
qryFunktionen_Übersicht.Sig_Status,
qryFunktionen_Übersicht.Sig_Strategie,
qryFunktionen_Übersicht.Sig_Prüfplan,
qryFunktionen_Übersicht.Plaus_Pfad,
qryFunktionen_Übersicht.Plaus_Info,
qryFunktionen_Übersicht.Plaus_Status,
qryFunktionen_Übersicht.Plaus_Strategie,
qryFunktionen_Übersicht.Plaus_Prüfplan,
qryFunktionen_Übersicht.Beschreibung_allgemein,
qryFunktionen_Übersicht.Funktionsname
FROM tb_KonzeptFunktionen RIGHT JOIN qryFunktionen_Übersicht
ON tb_KonzeptFunktionen.Funktion = qryFunktionen_Übersicht.Funktionsname
WHERE (((tb_KonzeptFunktionen.Konzept)=[Formulare]![frm_Fahrzeug]![ID]))
and this is another related query to above query:
SELECT tbFunktionen_Übersicht.*,
tbFunktionen.Funktionsname,
tbFunktionen.Funktionsbeschreibung,
tbFunktionen.diagnoserelevant,
tbFunktionen.ID AS FunktionsID
FROM tbFunktionen_Übersicht INNER JOIN tbFunktionen
ON tbFunktionen_Übersicht.Funktion = tbFunktionen.ID
ORDER BY tbFunktionen.Funktionsname, tbFunktionen_Übersicht.Fehlerpfadname;
I added an index to the fields that appear in ORDER oder JOINS but no effect
Would you please help me if possible?
Please refer to this post,hier you can find the answer
for me PDO brought improvement in my sql query's: http://www.php.net/manual/en/intro.pdo.php
//SQL-HANDLING*******************************************************//
//*********************************************************************//
//General Example-----------------
//$sqlHandling = new sqlHandling;
//$sqlHandling->connectSQL($sqlArray['host'], $sqlArray['user'],$sqlArray['pass'], $sqlArray['dbName']);
//$tableNameArray = $sqlHandling->showTablesSQL($sqlHandling->dbh);
class sqlHandling{
//PDO - Object/ callItOutside with: $sqlClass->dbh
public $dbh = null;
//connectDataBase-------------------//
//-----------------
//example: $dbh = connectSQL('localhost','admin','1admin','test');
//start transaction
//$dbh->beginTransaction();
//-----------------
//end transaction
//$dbh->commit();
//$dbh = null;
//-----------------
//1:SQL-Location
function connectSQL($host, $user, $pass, $dbname){
//endPrevTransaction
if($this->dbh != null){
$this->dbh->commit();
$this->dbh = null;
}
//establish connection
try{
$this->dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $pass);
$this->dbh->exec('SET CHARACTER SET utf8');
return $this->dbh;
}catch(PDOException $e){
print 'Error!: ' . $e->getMessage() . '<br/>';
die();
return FALSE;
}
}
//createColumnSQL-------------------//
//example: createColumnSQL($dbh, 'backupexample', array('SomeName1 VARCHAR(30)', 'SomeName2 VARCHAR(30)', 'SomeName3 VARCHAR(30)', 'SomeName4 VARCHAR(30)'));
//1:PDO connection/2:table/3:array holding columns
function createColumnSQL($dbh, $table, $columns){
//cicle through each array
foreach($columns as $tempColumn){
//set query
$query = 'ALTER TABLE `'.$table.'` ADD COLUMN '.$tempColumn;
//send the query
$stmt = $dbh->prepare($query);
//send the data
$stmt->execute();
}
}
}
This is only a working example for my PDO sqlHandling Class. I know retrieveAllValues won't help you further but you may adopt this code for your use.
MFG

how to remove NullExceptionError from Session Variable

I have a varible sem,which takes inputfrom the textbox but if the textbox is kept empty i want it to return "Please Enter a Semester"
int sem;
int parsevalue;
if (int.TryParse(TextBox2.Text, out parsevalue))
{
sem = parsevalue;
Session["Sem"] = sem;
}
else
{
Literal2.Text = "Please Enter a Semester";
}
But If the Textbox is empty the Session["Sem"] returns NullExceptionError in the .aspx file where i have used it.
I searched for the proper conversion using tryparse but could not understand it clearly as to how to print the above mentioned error message.
please help
Thank you in advance
The problem here is that you're assigning the Session variable only when there is a correct value, but you're always trying to access it. This will fail if the value is incorrect (and the Session variable is not set).
Here's your corrected code:
int sem;
int parsevalue;
if (int.TryParse(TextBox2.Text, out parsevalue))
{
sem = parsevalue;
}
else
{
Literal2.Text = "Please Enter a Semester";
}
//Always set the Session variable when it's used somewhere else
Session["Sem"] = sem;
Try:
HttpContext.Current.Session["Sem"] = sem;
Actually:
Session.Add("Sem", sem);
and
Session["Sem"] = sem;
is a same
Q1 Hi , I have a varible sem,which takes inputfrom the textbox but if the textbox is kept empty i want it to return "Please Enter a Semester"
int sem;
int parsevalue;
var txt = TextBox2.Text
if (!String.IsNullOrEmpty(text) && int.TryParse(text, out parsevalue))
{
sem = parsevalue;
}
else
{
Literal2.Text = "Please Enter a Semester";
}
Session["Sem"] = sem;