Failed to get data from localhost using php in android - php

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);

Related

How to insert data into table that contain foreing keys using php?

I am still learnig using php, and I got some problems.
So, I have a database named dbcoma and these tables;
pic of tables and the data
here is my question if I wanna make a registration for patient using php, what is the correct script?
I tried this one but it wasn't working (cant execute)
public function createPasien($id_alat, $id_patient, $passwordpas, $namepas, $age, $datein, $id_hospital, $id_alat){
$password = md5($passwordpas);
$stmt = $this->con->prepare("INSERT INTO `dbcoma`.`patient` (`id_patient`, `passwordpas`, `namepas`, `age`, `datein`, `id_alat`, `id_hospital`) VALUES (?, ?, ?, ?, ?, ?, ?);");
$stmt->bind_param("sssssss", $id_patient, $passwordpas, $namepas, $age, $datein, $id_alat, $id_hospital);
$stmt->execute();
// …
}
UPDATE: I FIXED IT AND FOUND THE PROBLEM. THANK YOU
There are some points to keep in mind:
Check the response return by execute() statement.
Echo the query and run it on the mysql terminal and see what happens.
While dealing with foreign key the value you are trying to insert must present in the master table, only then you can insert it in child table.

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.

Insert value does not match column list:1136

I am trying to insert a record to a table with 2 column but I get this error.
My error starts in part of the execute. Anyone that can help me out with this ?
I am using PDO.
My code:
global $conn_kl;
$sql = $conn_kl->prepare("INSERT INTO order_producten VALUES (?,?)");
$sql->execute(array($product_id, $bewerking_id));
The issue is here:
INSERT INTO order_producten VALUES (?,?)
here columns are not defined in this query, in this case it is expected that you have to pass the values for all columns in the table. But you want to insert the values for only 2 columns, so please please specify that columns names like:
INSERT INTO order_producten(column_name1, column_name2) VALUES (?,?)
order_producten will have more or less than two columns and you are setting only two values.
Please specify columns after table name. for example,
INSERT INTO order_producten(id, name) VALUES(?, ?)
For example, code something like this were working for me:
global $conn_kl;
$sql = $conn_kl->prepare("INSERT INTO `order_bewerkingen` VALUES (null, ?, ?, ?)");
$sql->execute(array($order_id, $method, $position));

MSSQL INSERT query failing for a specific table when called with PHP

I need to read the date that a request was created from our website. When that request is created, the information corresponding to that request and its meta-request is inserted in the DAI_REQ.REQUEST and DAI_REQ.META_REQUEST tables, respectively. We also have a dev server and a public deployment server. The problem happens only on our deployment server for some reason..
Unfortunately, the INSERT query to insert the information of the meta-request in the DAI_REQ.META_REQUEST table does not work, but the SELECT query I do right after does (so in my eyes, this removes any connection problems with the database/table itself). I also use the same syntax as the INSERT query I do on the DAI_REQ.REQUEST, so I do not think it is a query syntax problem. I also tried manually inserting as line within sql-server and it works fine. Finally, I echo'ed the value of $this->userId that I use as a parameter for the INSERT query to see if it contained the right ID, and it does. I did the same for the return value of $this->db->query(...), and it does NOT return anything (on our deployment server only).
I also know that my way of retrieving the last inserted row in a table is not perfect, but this is not the problem at hand here and it will be changed later on.
Here is the actual code where the problem happens:
public function dbInsert(){
// The actual problematic query
$this->db->query("INSERT INTO DAI_REQ.META_REQUEST ".
"(DATE_RECU, DATE_TERMINEE, USER_ID, STATUS) ".
"VALUES(GETDATE(), '', ?, 'R');", array($this->userId));
// This works fine though
$mr_select = $this->db->query("SELECT TOP 1 ID FROM DAI_REQ.META_REQUEST WHERE USER_ID = ? ORDER BY ID DESC;",
array($this->userId));
$mr_result = $mr_select->result_array();
$mr_id = $mr_result[0]['ID'];
$sim = 'N/A';
if(isset($this->recurrenceType))
$sim = 'Recurrent';
$this->db->query("INSERT INTO DAI_REQ.REQUEST ".
"(USER_ID, ASSIGNED_DATE, REQUEST_END_DATE, MODEL, EXPERIMENT, VARIABLE, START_DATE, END_DATE, ".
"LON_FROM, LAT_FROM, LON_TO, LAT_TO, RESOLUTION, FORMAT, SIMULATION, STATUS, ".
"CANCELLED_YN, PROJECT, MR_ID, URL_ORIGIN, DATE_EMAIL) ".
"VALUES(?, GETDATE(), '', ?, 'N/A', 'N/A', ?, ?, ?, ?, ?, ?, ?, ?, ?, 'R', 0, 'N/A', ?, ?, ?);",
array($this->userId, $this->model, $this->startDate, $this->endDate,
$this->lonFrom, $this->latFrom, $this->lonTo, $this->latTo,
$this->resolution, $this->format, $sim, $mr_id, $this->url_origin, $this->date_email));
$r_select = $this->db->query("SELECT TOP 1 ID FROM DAI_REQ.REQUEST WHERE USER_ID = ? ORDER BY ID DESC;",
array($this->userId));
$r_result = $r_select->result_array();
$this->id = $r_result[0]['ID'];
}
The database that the deployment server is using isn't set up to auto increment the ID column. In Microsoft SQL Server, for the ID column, you can set the Identity to Yes and Identity Increment to whatever number you want the ID column to increment by.

PHP PDO Invalid parameter number: parameter was not defined

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

Categories