INSERT INTO using PDO not inserting data - php

I am trying to get the data to insert into the specified database but it just wont. Ive looked at the manual tried examples and all of that but I cant get the data to pass through to the database I can however echo/print_r/var_dump it so I know I have data. Here is my code:
public function insertJson($url, $subId)
{
$json_file = file_get_contents(KHAN_BASE.$url.'/videos');
if(isset($json_file))
{
$json_decoded = json_decode($json_file, true);
}else{
$this->error = 'A valid JSON file was not specified';
}
// var_dump($json_decoded); <--- This return all of the data needed from the json pull so i know I have data
//m3u8, mp4, png,
//". $row['m3u8'] .",". $row['mp4'] .",". $row['png'] .",
foreach($json_decoded as $row)
{
//echo $row['backup_timestamp'].'<br/>'; <--- This outputs the correct information so I know I can access it that way
$sql = "INSERT INTO tbl_khan_videos (sub_subject_id, backup_timestamp, date_added, description,
duration, extra_properties, has_questions, ka_url, keywords, kind, position, readable_id, relative_url, title, url, views,
youtube_id) VALUES (:subid, :backup_timestamp, :date_added, :description, :duration, :extra_properties, :has_questions, :ka_url, :keywords, :kind, :position,
:readable_id, :relative_url, :title, :url, :views, :youtube_id)";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(":subid", $subId);
$stmt->bindValue(":backup_timestamp", $row['backup_timestamp']);
$stmt->bindValue(":date_added", $row['date_added']);
$stmt->bindValue(":description", $row['description']);
$stmt->bindValue(":duration", $row['duration']);
$stmt->bindValue(":extra_properties", $row['extra_properties']);
$stmt->bindValue(":has_questions", $row['has_questions']);
$stmt->bindValue(":ka_url", $row['ka_url']);
$stmt->bindValue(":keywords", $row['keywords']);
$stmt->bindValue(":kind", $row['kind']);
$stmt->bindValue(":position", $row['position']);
$stmt->bindValue(":readable_id", $row['readable_id']);
$stmt->bindValue(":relative_url", $row['relative_url']);
$stmt->bindValue(":title", $row['title']);
$stmt->bindValue(":url", $row['url']);
$stmt->bindValue(":views", $row['views']);
$stmt->bindValue(":youtube_id", $row['youtube_id']);
$stmt->execute();
}
}
Im not sure what I am doing wrong. I have tried binding it as an array (ex: $array = array(':subId' => $subId); $stmt->execute($array);) and still get no data through to the database. I know my config for the $this->db is good because I can pull other forms of already populated data with it. Any help would be very much appreciated.

I figured out my problem through some of the advice on here. What had been happening is I was trying to bind null values so the bindValue would cause the execute to go through without producing an error. Simple fix was doing this through foreach loops with a couple if statements which allowed me to set a value to the fields that were null. This solved the error. Again thank you to those who attempted to set in the correct path to finding the solution.

Related

Inset php json encoded array into database

I need to insert elements of a php encoded array into a database and I'm completely stuck. I have first used json encode to to grab data from the database using an SQL query (which I did successfully) but I now need to be able to do the opposite. If anyone could help I'd greatly appreciate it. It's my second day of work and I'm not doing so well. The following is my code:
$UserCoords_Query = "Select Accuracy, Longitude, Latitude, Timestamp
FROM UserDetails
WHERE UserId =" . $UserID;
$UserCoords_result = mysql_query($UserCoords_Query);
if (mysql_num_rows($UserCoords_result) == 0) {
echo "There are no users with an id of ". $UserID;
}
else {
$EmptyArray=array();
while ($row = mysql_fetch_array($UserCoords_result)) {
$Accuracy=$row['Accuracy'];
$Longitude= $row['Longitude'];
$Latitude=$row['Latitude'];
$Timestamp= $row['Timestamp'];
$Queue= array('Accuracy:' => $Accuracy, 'Latitude' => $Latitude, 'Longitude' => $Longitude, 'Timestamp' => $Timestamp);
array_unshift($EmptyArray,$Queue);
}
$ObjectResponse = array('Coords' => $EmptyArray);
echo json_encode($ObjectResponse);
$Json_Encoded= json_encode($ObjectResponse);
$Json_Decoded= json_decode($Json_Encoded, true);
$Update_Query= "INSERT INTO UserDetails (UserId, Accuracy, Latitude, Longitude, Timestamp)
VALUES ('".$UserID."','".$Json_Decoded[0] ['Accuracy']."','".$Json_Decoded[0]['Latitude']."',
'".$Json_Decoded[0]['Longitude']."','".$Json_Decoded[0]['Timestamp']."')";
mysql_query($Update_Query) or die(mysql_error());
I agree with chandresh_cool. you should use 'true' option to decode the json encoded string as array, otherwise it will return an object.
moreover, file_get_contents() expects a filename (with full or relative path). When you try to give a json_encoded string, it thinks that its the file name and it will try to open it as a file, which, obviously does not exist, and thus throws an error. Try to give an existing filename and see that solves the problem.
P.s. I know this should be a comment, but due to insufficient points, I cannot comment
You need to set second parameter of json_encode as true to return array
$Json_Decoded = json_decode($Json_Encoded, true);

Data is not being inserted into second table (MYSQLi)

I am using the code below that uploads a file and inserts data into the "Image" table using mysqli:
<?php
session_start();
$username="xxx";
$password="xxx";
$database="mobile_app";
$mysqli = new mysqli("localhost", $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$result = 0;
//UPLOAD IMAGE FILE
move_uploaded_file($_FILES["fileImage"]["tmp_name"], "ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
//INSERT INTO IMAGE DATABASE TABLE
$imagesql = "INSERT INTO Image (ImageFile) VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s", $img);
//Assign the variable
$img = 'ImageFiles/' . $_FILES['fileImage']['name'];
$insert->execute();
//RETRIEVE IMAGEID FROM IMAGE TABLE
$lastID = $mysqli->insert_id;
//INSERT INTO IMAGE_QUESTION DATABASE TABLE
$imagequestionsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionId) VALUES (?, ?, ?)";
if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) {
// Handle errors with prepare operation here
}
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$insertimagequestion->bind_param("sss", $lastID, $sessid, $_POST['numQuestion'][$i]);
$insertimagequestion->execute();
//IF ANY ERROR WHILE INSERTING DATA INTO EITHER OF THE TABLES
if ($insert->errno) {
// Handle query error here
}
$insert->close();
if ($insertimagequestion->errno) {
// Handle query error here
}
$insertimagequestion->close();
}
}
?>
So for example if I insert 2 images "cat.png" and "dog.png" into "Image" Database table, it will insert it like this:
ImageId ImageFile
220 cat.png
221 dog.png
(ImageId is an auto increment)
Anyway what I want to do is that when a file is uploaded, not only is the data inserted into the table above, but I want to also be able to retrieve the ImageId that was inserted above and place it in the "Image_Question" table below so it would be like this:
ImageId SessionId QuestionId
220 cat.png 1
221 dog.png 4
The problem is that it is not inserting any data into the second table "Image_Question", does anyone know why it is not inserting any data? There is no errors in the php file.
To upload a file, the user selects a file for the ajax uploader in the "QandATable.php" page, when the user clicks on upload, using AJAX it will go onto the imageupload.php page and does the uploading there. So the problem I have is that no errors will appear as they are on seperate pages.
First, save the insert ID gained from your record addition (after the $insert->execute):
$lastID = $mysqli->insert_id;
Then reference $lastID later.
To pull up my comment from below:
$lastID = $insert->insert_id;
I think it's to do with swapping the handle names around - $mysqli, $insert etc.
Hope I read the question correctly...
Check for 500 Error responses in Firebug -> Net tab/Chrome Developer tools -> Network tab . Even if nothing is returned as text, this will help you debug a syntax/semantic error as opposed to a logical error.
Firstly, what happens when you echo $lastID? Do you get a value output to the screen?
If not, we need to fix that first so that $lastID is returning the correct value.
Your insert code appears to be correct.
You should get the Last inserted ID from first table and insert into your 2nd table (Image_Question) .
I Don't know the PHP coding, but this task is simple as well.Because this operation will be executed inside DAO class.So, No matter whether it is PHP or JAVA.
If the second insertion fails, then
if ($insertimagequestion->error) {
// Handle query error here
echo $insertimagequestion->error;
}
This should tell you what the Error being thrown from the execution of the statement is.
Your PHP code seems fine, the error could be due to a Foreign key constraints or any other constraints on your DB Tables.
PS: I think you should validate the type of files you allow to be uploaded so people can't upload *.php or *.js files, this can lead to catastrophic XSS attacks.
Also try to avoid using the same filename as uploaded by the user, you may want to prefix with some random variable, so you can now have
//notice uniqid(time()) for randomness, also move the declaration of $img higher
//Assign the variable
$img = "ImageFiles/" . uniqid(time()) . $_FILES["fileImage"]["name"];
move_uploaded_file($_FILES["fileImage"]["tmp_name"], $img);
...
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s", $img);
Bind with mysqli works with references to variables. I dont think your last argument in the second bind command references the way you expect it to.
Assign the the last argument $_POST['numQuestion'][$i] to a variable and use this variable in the bind method call. I am guessing this is either not defined, evaluating to null, and the bind is failing since you can't bind a null as a string or bind cannot use a multidimensional array since itexpects a variable passed as reference.
Try this:
//Below will set a default value of empty string if the POST variable is not set
$postVar = isset($_POST['numQuestion'][$i])?$_POST['numQuestion'][$i]:'';
$insertimagequestion->bind_param("sss", $lastID, $sessid, $postVar);
After doing this, if you see entries in the DB with a '' in the QuestionId column, $_POST['numQuestion'][$i] isn't being set and you have something wrong elsewhere in your code having nothing to do with DB access.
Tried to figure out where could be the failure.
There is no problem with second query and you get successfully last insert id. I used static values for the variables for second query it worked fine. Even you can hardcode values n check out.
Take care of the foll:
Does bind params get the all the values?
print_r() $lastID, $sessid, $_POST['numQuestion'][$i]
This Will not create problem unless database has contraints of not accepting empty or null values.
Make use of the check condition to find where its going wrong.
if (!$insertimagequestion = $mysqli->prepare("$imagequestionsql")) {
// Handle errors with prepare operation here
echo "Prepare statement err";
}
if ($insert->errno) {
// Handle query error here
echo "insert execution error";
}
Though its an ajax you can use Developer Tool of Chome to debug ajax requests.
Press F12 to open the Developer Tool in Chrome
Go to Network Tab >> Perform action for ajax requests to be sent on your form >> you can find the ajax requests sent >> click on it >> Click on the "Response" Tab you will find the error if you have
echoed or the response. So, echo error and print_r() to help debugging

Insert to more than one table with PHP:PDO on MSSQL

I'm trying to write a php function which is going to put values to two diferent tables, but it dsn't work. How should I do?
public function AddKursplanering($kursBudgetId, $momentId, $momTypID, $pId, $rollId, $tid, $utfall)
{
if($stmt = $this->m_database->GetPrepareStatement(" INSERT INTO Kursmoment(KBID, MomentID, MomTypID)
VALUES(:kursBudgetId, :momentId, :momTypID)
INSERT INTO Uppgift (KMID, PID, RollID, Tid, Utfall)
VALUES (##IDENTITY, :pId, :rollId, :tid, :utfall)"))
{
$stmt->bindValue(':kursBudgetId', $kursBudgetId,PDO::PARAM_INT);
$stmt->bindValue(':momentId', $momentId,PDO::PARAM_INT);
$stmt->bindValue(':momTypID', $momTypID,PDO::PARAM_INT);
$stmt->bindValue(':pId', $pId,PDO::PARAM_INT);
$stmt->bindValue(':rollId', $rollId,PDO::PARAM_INT);
$stmt->bindValue(':tid', $tid,PDO::PARAM_INT);
$stmt->bindValue(':utfall', $utfall,PDO::PARAM_INT);
if($stmt->execute())
{
$stmt->CloseCursor();
return true;
}
return false;
}
}
If you are getting an error, post the error text
If it is not an error, but it is not working for some reason, state clearly what part doesn't work
Now, that should actually work, but use SCOPE_IDENTITY() instead of ##IDENTITY, which may return you an unrelated number if there are triggers involved.
Also, consider encapsulating such logic in a stored procedure with the parameters, so you can call a single proc that does both inserts (essentially the same code)
Without knowing the error message from the query above it look like you need to have a semi-colon between the statements. Without it, it will be interpreted as one query instead of two.
if($stmt = $this->m_database->GetPrepareStatement("
INSERT INTO Kursmoment(KBID, MomentID, MomTypID)
VALUES(:kursBudgetId, :momentId, :momTypID);
INSERT INTO Uppgift (KMID, PID, RollID, Tid, Utfall)
VALUES (##IDENTITY, :pId, :rollId, :tid, :utfall)"))

PHP mysql insert associative array into database from a "dynamic" form

I have a form that allows for the duplication of fields. The form is posted via php and inserted into a database. My problem is I cannot seem to loop through the array correctly. Am I setting up the form correctly (are the name's formatted correctly) and am I looping through the arrays correctly? I am not successful in getting any data inserted.
The trick is that the duplicated fields need to stick together.
Think of the fields as sets of questions and answers.
Each question has a title, the question text and a file input.
Each answer has a title, the answer text a file input, and a check box to note the correct answer.
I have the name's set up like so:
name='question[1][title]'
name='question[1][text]'
name='question[1][file]'
answer[1][title][]
answer[1][text][]
answer[1][file][]
answer[1][correct][]
The php to insert the form is as follows:
$insert_question = $db->prepare(
'insert into questions (title, text) values (?, ?)');
$insert_answer = $db->prepare(
'insert into answers (question_id, title, text, correct)'.
' values (?, ?, ?, ?)');
foreach ($_POST['question'] as $q_num => $q)
{
$insert_question->execute(array($q['title'], $q['text']));
$q_id = $db->lastInsertId();
//********************
// insert files
//********************
foreach ($_POST['answer'][$q_num] as $a)
{
$insert_answer->execute(
array($q_id, $a['title'], $a['text'], $a['correct']));
}
}
Sorry that this is such a huge question. I have been working on this for two days now and have run out of ideas.
I'm not sure I understood your problem (I don't speak english fluently).
But here you need an other loop instead of this one:
foreach ($_POST['answer'][$q_num] as $a)
{
$insert_answer->execute(
array($q_id, $a['title'], $a['text'], $a['correct']));
}
like :
$lim = count($_POST['answer'][$q_num]['title']);
for($i=0;$i<$lim;++$i){
$insert_answer->execute(
array($q_id, $_POST['answer'][$q_num]['title'][$i], $_POST['answer'][$q_num]['text'][$i], $_POST['answer'][$q_num]['correct'][$i]));
}
It didn't test anything and it should work only if you always get title, text and correct in an answer.
The issue is with the second loop (answer array). Try this
<?php
foreach ($_POST['answer'][$q_num]['title'] as $a => $value)
{
$insert_answer->execute(
array($q_id, $_POST['answer'][$q_num]['title'][$a], $_POST['answer'][$q_num]['text'][$a], $_POST['answer'][$q_num]['correct'][$a]));
}
?>

Issue with Inserting a record into a MySql database

I am having an issue with a simple form uploading script.
On this upload script I built to upload data to a MySql database, I can't seem to get the record to insert into the database when I include this one variable.
I figured that perhaps I am overlooking some minor coding issue, and I'm working on a deadline to get this system live...
Here is the code snippit that is giving me issues.
$title=$_REQUEST['title'];
$author=$_REQUEST['author'];
$hours=$_REQUEST['hours'];
$start_d=$_REQUEST['start_d'];
$start_m=$_REQUEST['start_m'];
$start_y=$_REQUEST['start_y'];
$end_d=$_REQUEST['end_d'];
$end_m=$_REQUEST['end_m'];
$end_y=$_REQUEST['end_y'];
$certificate=$_REQUEST['certificate'];
$required=$_REQUEST['required'];
$assessment=$_REQUEST['assessment'];
$describe=$_REQUEST['description'];
$query=mysql_query("INSERT INTO `records` (title, hours, start_date_d, start_date_m, start_date_y , end_date_d, end_date_m, end_date_y , certificate, requirement, author, approved, assessment, describe) VALUES ('$title', '$hours', '$start_d', '$start_m', '$start_y', '$end_d', '$end_m', '$end_y', '$certificate', '$required', '$author', '0', '$assessment', '$describe')");
mysql_close();
The variable that is giving me issues is the one denoted as '$describe'.
My previous testing has indicated:
The form script is collecting data correctly
The form script is passing the data to the upload script correctly via method='post'
The database connection information is correct
All of the field names in the mysql query are typed correctly
Thank you in advance for your help.
Update:
echo mysql_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 ' assessment, describe) VALUES' at line 1
this awful code should be totally rewritten.
but to solve this very problem
foreach ($_REQUEST as $key => $value) $_REQUEST[$key] = mysql_real_escape_string($value);
Something like this.
Note that i've changed date fields to date format.
$_POST['start_date'] = $_POST['start_y'].'-'.$_POST['start_m'].'-'.$_POST['start_d'];
$_POST['end_date'] = $_POST['end_y'].'-'.$_POST['end_m'].'-'.$_POST['end_d'];
$_POST['approved'] = 0;
$fields = explode(" ","title author hours start_date end_date certificate required assessment describe");
$query = "INSERT INTO `records` SET ".dbSet($fields);
mysql_query($query) or trigger_error(mysql_error().$query);
function dbSet($fields) {
$q='';
foreach ($fields as $v) $q.="`$v`='".mysql_real_escape_string($_POST[$v])."', ";
return trim($q,", ");
}
Try this:
$query="INSERT INTO `records` (title, hours, start_date_d, start_date_m, start_date_y , end_date_d, end_date_m, end_date_y , certificate, requirement, author, approved, assessment, describe) VALUES ('$title', '$hours', '$start_d', '$start_m', '$start_y', '$end_d', '$end_m', '$end_y', '$certificate', '$required', '$author', '0', '$assessment', '$describe')";
var_dump($query);
And post to us :)
It turns out that "Describe" is a reserved word in MySql.
I changed the field name, and now my script works...

Categories