PHP PDO Invalid parameter number: parameter was not defined - php

This is my code :
It gives no error when i change the array to index type instead of associative.
But the moment i change it back to associative it starts giving error.
Any help on this ?
$dbh=new PDO("mysql:host=localhost;dbname=sj_db", 'root', '');
$entryData = array(
"Team Name"=>$_POST['name']
, "Won"=>$_POST['w']
, "Lost"=>$_POST['l']
, "Draw"=>$_POST['d']
, "Points"=>$_POST['p']
);
$sql="INSERT INTO fb (`Team Name`, Won, Lost, Draw, Points) VALUES (?, ?, ?, ?, ?)";
$sth=$dbh->prepare($sql);
//$sth->execute($entryData[`Team Name`],$entryData['Won'],$entryData['Lost'],$entryData['Draw']
// ,$entryData['Points']);
$sth->execute($entryData);
//$sth->closeCursor();

Placeholders in your query are positional (?) ones.
Either change them to named (:name)
or pass array_values($entryData) into execute
Though you have to remove a space from Team Name key in order to use named placeholders

Related

Failed to get data from localhost using php in android

Im new at Android. I'm trying to fetch some data from localhost server. My query is running perfectly on phpMyAdmin But I facing error in api. I have very little knowledge about Php so did not get what the issue is.
Code:
public function saveUserProgress($user_id,$course_id,$topic_id,$quiz_marks){
$output = $this->con->prepare("INSERT INTO user_progress (user_id, course_id, topic_id,quiz_marks)
VALUES (?, ?, ?,?)
ON DUPLICATE KEY UPDATE
user_id=?, course_id=?, topic_id=?, quiz_marks = quiz_marks + ?");
$output->bind_param("iiii",$user_id,$course_id,$topic_id,$quiz_marks);
if($output->execute()){
return PROGRESS_SAVED;
}else{
return ERROR_OCCUR;
}
}
Error:
{"error":true,"message":403}
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement
If as you said your unique key is user_id and course_id then you do not need to update them on duplicate key. You only need to update the remaining 2 values. Together with the 4 you wanted to add it makes 6 placeholders, so you need to bind 6 variables.
$output = $this->con->prepare("INSERT INTO user_progress (user_id, course_id, topic_id,quiz_marks)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
topic_id=?, quiz_marks = quiz_marks + ?");
$output->bind_param("iiiiii", $user_id, $course_id, $topic_id, $quiz_marks, $topic_id, $quiz_marks);

MySQL INSERT inserting BIT to 1 instead of 0

I have the following query which should insert a 0 but instead inserts 1.
It is executed with prepared statements in PHP:
$insertsql=
"INSERT INTO table1 (column1, column2, column3, column4, column5, column6)
VALUES (?, ?, ?, ?, ?, ?)";
$insertstmt = $pdo->prepare($insertsql);
$insertstmt->execute(array($var1, $var2, $var3, $var4, $var5, 0));
All inserts are performed fine, except a 1 is inserted in column6 instead of a 0.
Column 6 has the datatype BIT.
The query works fine, however, when executing
INSERT INTO table1 (column6) VALUE (0);
directly in the phpmyadmin 'MySQL' tab.
What am I missing?
EDIT:
Using
$insertstmt->execute(array($var1, $var2, $var3, $var4, $var5, false));
works as expected. Why is 0 working directly within a SQL query but not when using pdo to execute it?
You need to explicitly declare this parameter as Boolean when passing it to PDO.
From the PDO execute documentation :
input_parameters
An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.
This is not what you want.
So you would need to change your logic to avoid using the execute(array()) construct and bind each parameter individually, using bindValue(). For boolean :
$insertstmt->bindValue(':col6', false, PDO::PARAM_BOOL);
Since booleans are just TINYINT(1) in MySQL, PDO::PARAM_INT should work fine as well :
$insertstmt->bindValue(':col6', 0, PDO::PARAM_INT);
Finally : if this boolean value will always be false, then you may pass it directly to the query, like :
$insertstmt->execute(array($var1, $var2, $var3, $var4, $var5, false));
As wisely commented by spencer7593, another option is to do the type casting from within the SQL. For example one could convert the string to a bit value with :
INSERT INTO table1 (column1, column2, column3, column4, column5, column6)
VALUES (?, ?, ?, ?, ?, IF( ? ='0', b'0', b'1') )

How to use an Oracle sequence from PHP ODBC function

When trying to insert this problem generates me. Use of the undefined constant SEQUENCE_ID_PROBLEMA - assumed SECUENCIA_ID_PROBLEMA
I do not know where the problem is, please help.
My Oracle sequence:
<code>
CREATE SEQUENCE INFORMACION.SECUENCIA_ID_PROBLEMA
START WITH 0
MAXVALUE 9999999999999999999999999999
MINVALUE 0
NOCYCLE
NOCACHE
NOORDER;
</code>
My code in PHP:
<code>
$sql = "INSERT INTO $tabla (ID_PROBLEMA, HORA_INICIO, PROBLEMA, CAUSA,
SOLUCION, HORA_FIN, ID_ASIGNACION) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = odbc_prepare($Conex, $sql);
$success = odbc_execute($stmt,[SECUENCIA_ID_PROBLEMA.nextval,$HORA_INICIO,$PROBLEMA, $CAUSA,SOLUCION,sysdate, $ID_ASIGNACION] );
</code>
PHP and SQL are entirely different languages and what you're getting is a PHP warning triggered by the PHP interpreter:
define('FOO', 3.1416);
echo FOO; // 3.1416
echo BAR; // Warning: Use of undefined constant BAR - assumed 'BAR' (this will throw an Error in a future version of PHP)
Your code tries to handle the sequence name as dynamic input. You cannot use prepared statements for that because the whole purpose of prepared statements is to prevent that from happening. If you really have to, you need to generate the basic SQL skeleton with plain string functions:
$table = 'PROBLEMA';
$sequence = 'SECUENCIA_ID_PROBLEMA';
$sql = "INSERT INTO $table (ID_PROBLEMA, HORA_INICIO, PROBLEMA, CAUSA,
SOLUCION, HORA_FIN, ID_ASIGNACION) VALUES ($sequence.nextval, ?, ?, ?, ?, ?, ?)";
INSERT INTO PROBLEMA (ID_PROBLEMA, HORA_INICIO, PROBLEMA, CAUSA,
SOLUCION, HORA_FIN, ID_ASIGNACION) VALUES (SECUENCIA_ID_PROBLEMA.nextval, ?, ?, ?, ?, ?, ?)
However, your code also tries to feed the dynamic bound variable with a fixed hard-coded text. I wonder if this extra complexity is intentional and necessary. Having different tables with the same exact column names is a potential code smell :)
In the end you can not use the sequence from php. What I did was create a trigger in the Oracle Data Bae so that it executes the sequence when insert a new row
<code>
CREATE SEQUENCE INFORMACION.SECUENCIA_ID_PROBLEMA
START WITH 0
MAXVALUE 9999999999999999999999999999
MINVALUE 0
NOCYCLE
NOCACHE
NOORDER;
CREATE TRIGGER problema_on_insert
BEFORE INSERT ON PROBLEMA
FOR EACH ROW
BEGIN
SELECT SECUENCIA_ID_PROBLEMA.nextval
INTO :new.ID_PROBLEMA
FROM dual;
END;
</code>

php mysqli repeated fields in prepared statement

I need to convert an existing project from mysql to mysqli and using prepared statement.
In the existing project there are queries that uses repeated variable values.
One such example is this: where the $prev_yr is used 3 times.
$sqlins = "Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)
select StudentID, '$prev_cl', '$prev_yr', '$prev_lvl', '', '123456789', '$prev_yr-01-01', '$prev_yr-12-31' from student Where StudentID in ($ids) ";
Is there a better method than this:
$sqlins = "Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)
select StudentID, '?', '?', '?', '', '123456789', '?-01-01', '?-12-31' from student Where StudentID in (?) ";
$stmt = $mysqli->prepare($sqlins);
$stmt->bind_param("ssssss", $prev_cl,$prev_yr,$prev_lvl,$prev_yr,$prev_yr,$ids);
$stmt->execute();
I am wondering if there is a way of binding the $prev_yr once for all 3 occurrences.
Because there are other queries that may have 2 occurrences of $prev_lvl, 5 occurrences of $prev_yr etc in one statement. The idea is that when the repeated occurrences of multiple variables becomes many in a statement - it becomes quite confusing to arrange them in the bind_param.
Any solution?
Thank you.
Does it even work like that, typical you wont't do this '?-01-01' in a query. I haven't used Mysqli, in about 4 years, as all I use now a days is PDO. But as far as I know when you send that to prepare it's gonna puke on the ? being in a string.
I would split it, there actually is no real need to do the select because the only thing being selected is the studentID which you already have. Simply
$insert = $mysqli->prepare("Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
foreach( $ids AS $id ){
$stmt->bind_param("issssiss", $id, $prev_cl,$prev_yr,$prev_lvl,'', '123456789', $prev_yr.'-01-01',$prev_yr.'-12-31');
$stmt->execute();
}
I can't test it so hopefully I got everything in the right place.
As I said I don't think you can bind to the Fields part of the query and certainly not inside a partial string, besides it's making a select that is un-needed. Just make sure to prepare the insert before the loop.
Just to clearly the only thing that select actually gets from the DB is this
select StudentID ... from student Where StudentID in (?)
The rest are added in as "fake" columns, I don't know the term for it. It's difficult to read the original query..
I am wondering if there is a way of binding the $prev_yr once for all 3 occurrences.
No.
Besides, it wouldn't work this way anyway, as you cannot bind just an arbitrary query part of your choice. You can bind a complete data literal only. Means instead of '?-01-01' it should be just ?, whereas in your PHP code you should make it
$dateStart = "$prev_yr-01-01";
and then bind this variable for the whole value. So there will be no more repeating variables.

broken prepared statement for insert

I cannot for the life of me figure out why this prepared statement isn't working.
$thisInsert = $db->prepare("INSERT INTO conversations (person_a, person_b, exchange_count, inbox) values(?, ?, ?, ?)");
$thisInsert->bind_param('iiii', $activeUser, $passiveUser, 1, 1);
$thisInsert->execute();
Values are bound by reference, not by value; so you can't bind a value like 1, only something like a variable containing the value that you want to bind
Quoting from the manual (my emphasis)
Note that mysqli_stmt_bind_param() requires parameters to be passed by reference

Categories