Unable to Get Response Header from Php PDO on Google App Engine - php

I am trying to send back the last inserted id after I insert some data into my database. I am successfully entering the data into the database, but there is no response data being sent back. I am using Php PDO and it is hosted on Google App Engine and my headers are set to application/json in the dbconnect.php file. What do I need to add to make it successfully send back response data.
<?php
require('dbconnect.php');
$statement=$con->prepare('INSERT INTO customers (fname, lname) VALUES (:fname,:lname)');
$statement->execute(array(':fname' => $_POST['fname'], ':lname' => $_POST['lname'] ));
$orderId = $statement->lastInsertId();
$json = $json_encode($orderId);
echo $json;
$con = null;
?>

I got Notice: Undefined index: fname and Notice: Undefined index: lname and Fatal error: Call to undefined method PDOStatement::lastInsertId() – Moustache_Me_A_Question 10 mins ago
You have no name attributes for the form elements.
Therefore you need to add them to your elements.
Here is an example form you can base yourself on:
<form action="" method="post">
First name:
<input type="text" name="fname">
<br>
Last name:
<input type="text" name="lname">
<br>
<input type="submit" name="submit" value="Submit">
</form>
That is why you're getting undefined index notices.
$json = $json_encode($orderId); should read as $json = json_encode($orderId); - json_encode() shouldn't be a variable but the function itself.
http://php.net/manual/en/function.json-encode.php
Also:
$orderId = $statement->lastInsertId();
to
$orderId = $con->lastInsertId();
which is why you're getting this message:
Fatal error: Call to undefined method PDOStatement::lastInsertId()
lastInsertId() is a method of the PDO class, not the PDOStatement class.
which I found in Bill Karwin's answer when Googling the error:
https://stackoverflow.com/a/8580768/

Related

Single dimensional array becomes multidimensional after submit

I have done my research and cannot find an answer so now I'm here to seek out professionals' advice.
I have a query which returns an array in model:
$sql = "SalesList ";
$sql = $sql."'".$current_company_code."', ";
$sql = $sql."'".trim($current_user_id)."', ";
$sql = $sql."'".$as_date."', ";
$sql = $sql.$language_no;
$DB=$this->load->database($current_database,TRUE);
$query = $DB->query($sql);
return $query->result();
In controller: I passed the result to $data['sales_list'] and load to view
$data['sales_list'] = $this->SalesList->GetSalesList($current_database,$current_company_code,$current_user_id,date('Y-m-d 23:59:59'),$language_no);
$this->load->view('Sales_Record', $data);
In view:
<?php foreach ($sales_list as $record): ?>
<input type="hidden" name="sp_name_d[]" id="sp_name_d[]" value="<?php echo set_value('sp_name_d[]',trim($record->sp_name));?>"/>
<?php endforeach; ?>
Problem:
Upon submit, the same coding (which presents no issue on first load) prompted the following error:
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Line Number: 39
Array"/>
Line no 39 refers to:
<input type="hidden" name="sp_name_d[]" id="sp_name_d[]" value="<?php echo set_value('sp_name_d[]',trim($record->sp_name));?>"/>
Help needed. Thank you.
Sincerely, blossoming programmer.
[Update] Cause of issue (Rookie mistake):
I have some codes in view that use index in set_value (for radio button reference) which leads to multidimensional array:
<input type="radio" name="status_d[<?php echo $counter;?>]" id="status_d[]" value="1" <?php echo set_value('status_d['.$counter.']', '1', $record->status==1); ?> checked />
Solution:
in view added index in set_value:
<input type="hidden" name="sp_name_d[]" id="sp_name_d[]" value="<?php echo set_value('sp_name_d['.$counter.']',trim($record->sp_name));?>"/>
The Problem is:
set_value() - The first time there is no input so it becomes an empty string, but after submit it is an array which remains array.
On an Fresh load of a page there is no previous input data, So everything is empty in Form When setting via set_value.

Searching through a database with PHP - Session already started [duplicate]

This question already has answers here:
PHP sessions that have already been started [duplicate]
(11 answers)
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
I have developed a simple search page but I can't seem to get it to work. I'm faced with 2 problems, which I think are linked. When I go on the search form page, the error:
Notice: Undefined index: userlogged in header.php on line 36 Notice: Undefined index: adminlogged in header.php on line 59`
And when using the search form using valid test data, these errors are shown:
Notice: A session had already been started - ignoring session_start() in header.php on line 3 Notice: Undefined index: userlogged in header.php on line 36 Notice: Undefined index: adminlogged in header.php on line 59
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in search.php on line 12
I wont post the header.php as I think it's because of the bind_result, however I'm not sure how I've done this wrong.
I have tried removing the session_start() from header.php so it's not included automatically, but that just throws this error:
Notice: Undefined variable: _SESSION in header.php on line 36 Notice: Undefined variable: _SESSION in header.php on line 59
Searchform.php
<?php
ob_start();
error_reporting(E_ALL);
?>
<br><br><br>
<?php
ini_set('display_errors', -1);
include 'header.php';
include 'connection.php';
?>
<br /><br />
<html>
<header>
<link rel="stylesheet" type="text/css" href="web.css" />
<link rel="stylesheet" type="text/css" href="/web.css" />
</header>
<body>
<center>
<h2>Search for people</h2>
<br />
Please enter the name you wish to search for<br /><br />
<form method="post" action="search.php" id="searchform">
<input type="text" name="name">
<input type="submit" name="searchsubmit" value="Submit">
</form>
<br /><br/>
Or search people by category
</center>
</body>
</html>
Search.php
<?php
if(isset($_POST['searchsubmit']))
{
include 'searchform.php';
include 'header.php';
$name = $_POST['name'];
if ($stmt = $connection->prepare ("SELECT * FROM users WHERE Username = ?"))
{
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($personresult);
$stmt->fetch();
print_r($personresult);
}
else
{
echo "<p>Please enter a search query</p>";
}
}
else
{
echo "NOT SET!";
}
?>
Without knowing what the columns are in your database, I can only give a partial response to what you are doing wrong with the bind_result.
But before that, you are going to run in to an issue with sessions and your header stuff because you are showing all notices. I would suggest starting it on the requested pages rather than your includes. So right after you start the script, make the call to session_start() and don't make it anywhere else. Note that it must go before any output.
Now, for the bind_result. What the error message is telling you is that you are selecting more from your table than just one column. ie, you might be selecting a userid, uname, realname, etc. But when you bind the result, you are only giving it room for one of those. So a basic example to show you the relationship, I'll modify your select slightly:
$stmt = $connection->prepare ("SELECT userId, userName, realName FROM users WHERE Username = ?")
Then when you bind your result, you will want to do something like:
$stmt->bind_result($userId, $userName, $realName);
For each column you select in your statement, you need a variable to represent it within your bind_result call.

php throwing undefined index warning but the script works as intended?

I wrote a simple php script that basically echos the values put into a form on the page, later, I will have this write to a DB but I was working on troubleshooting it before I did that since I keep getting this warning.
Does anyone know why I am getting it? If I just fill in the fields and submit the form, the script works fine and the warning disappears.
PHP Function:
function quickEntry()
{
$subTitle = $_POST['subTitle'];
$subDetails = $_POST['details']; //This is line 13 in my code
echo "$subTitle";
echo "<br>$subDetails";
}
HTML / PHP Code:
<form method="post" action="">
<hr>
<h1>Quick Entry:<p></h1>
Subject Title:<br> <input type="text" name="subTitle"><br><br>
Subject Details: <p><textarea name="details" placeholder="Enter Details here..."></textarea><p><br>
<input type="submit" name="QuickEntrySubmit" value="Submit Quick Entry" /><br>
</form>
<?php
if (isset($_POST['QuickEntrySubmit']))
{
quickEntry();
}
?>
I know that I could disable warnings and I wouldn't see this, but I really just want to know why php is throwing the warning so I can fix the syntax appropriately and keep my code clean going forward. Full warning is:
Notice: Undefined index: details in C:\xampp\htdocs\test1.php on line 13
Thanks!
The reason why you are getting that error is because you are not checking whether the 'subTitle' and 'details' inputs have values in them.
Your code should work well like this:
function quickEntry(){
$subTitle = isset($_POST['subTitle'])? $_POST['subTitle']: null;
$subDetails = isset($_POST['details'])? $_POST['details']: null ; //This is line 13 in my code
if(!is_null($subTitle) && !is_null($subDetails)){
echo "$subTitle";
echo "<br>$subDetails";
} else{
//blah blah blah
}
You get the warnings because the $_POST variables with the indexes that you're checking for ($_POST['subTitle'] & $_POST['details']) aren't set, so the variables are empty as you reference something that isn't there.
You should do a check to ensure they are set first before trying to assign them to a variable:
$subTitle = (isset($_POST['subTitle']) && !empty($_POST['subTitle'])) ? $_POST['subTitle'] : null;
$subDetails = (isset($_POST['details']) && !empty($_POST['details'])) ? $_POST['details'] : null;
The above code will check to ensure the post index isset() and isn't empty() before assigning it to the variables.
NOTE
The variables are set when you submit the form because you are actually posting the data to the script.
You see the input attribute name? When you submit the form, they are the relevant $_POST indexes.
Just remember to ensure that the values aren't empty if you intend to print them to the markup.

Undefined variable result when trying to echo a value from a query using php

I am trying to get some information out of a query and into the values of some inputs, the parameter that it sends to display the specific information is a ID that is being send like this:
PHP on a includes file:
<a href="modificarLab.php?idlab='.$row['idlab'] .'">
<input type = "submit" value = "Modificar" class= "btnModificar" id = "btnModificar-'.$row['idlab'].'"
style="position:absolute;left:170px;top:192px;"/>
</a>
When I click the above link it sends me to another page that reflects the idlab on the URL, so it shows idlab= X, where x depends on the idlab of the button clicked, this part seems to be working just fine.
The problem comes when trying to get the information into the inputs'values, in a example I used as reference they used the exact same syntax (including the part above with the href)and it is working, so I don't know what could I be doing wrong. This is how my code looks:
On the page the href refers to:
UPDATED php:
<?php
isset($_POST['lab']) ? $_POST['lab'] : 'Unknown';
$result = getSpecificLabModify($_GET['lab']);
?>
<form id="frmLabs" method="post">
<?php
if (isset($_GET['idlab'])){
$result = getSpecificLabModify($_GET['idlab']);
}
?>
<label for="txtCapacidad">Capacidad</label>
<input type="text" name="txtCapacidad" id="txtCapacidad" value="<?php echo utf8_encode($result['capacidad'])?>">
<label for="txtNumLab">Código de laboratorio</label>
<input type="text" name="txtNumLab" id="txtNumLab" value="<?php echo utf8_encode($result['codigolab'])?>">
<label for="txtUbicacion">Ubicación</label>
<input type="text" name="txtUbicacion" id="txtUbicacion" value="<?php echo utf8_encode($result['ubicacion'])?>">
But instead of the values inside I am getting the error:
EDIT ERROR:
Notice: Undefined index: idlab in C:\wamp\www\Proyecto\modificarLab.php on line 66
Just in case the function to get the information is this one:
On the includes PHP file:
function getSpecificLabModify($pId){
$query = "SELECT * FROM labs WHERE idlab=$pId";
$result = do_query($query);
$row = mysql_fetch_assoc($result);
return $row;
}
I've tried a lot of things but so far nothing has yielded any results. Thanks in advance.
You're using $_GET not $_POST. So change:
isset($_POST['lab']) ? $_POST['lab'] : 'Unknown';
to:
isset($_GET['lab']) ? $_GET['lab'] : 'Unknown';

Using a form to append Nodes to XML using PHP

I'm really new to PHP and Im trying to append Nodes to XML using PHP.
This is my comments.php file:
<?php
$date = "http://jdrag.x10.mx/comments_file.xml";
$xml = simplexml_load_string($data);
$commentt = $xml->addChild("comment");
$name = $_POST["cname"];
$email = $_POST["cemail"];
$comment = $_POST["comment"];
$commentt->addChild("name", $name);
$commentt->addChild("email", $email);
$commentt->addChild("commentInside", $comment);
echo $xml->saveXML();
?>
My comments.html is:
<form action="comments.php" method="post">
Name: <input type="text" name="cname" />
Email: <input type="text" name="cemail" />
Comment: <input type="text" name="comment" />
<input type="submit" />
</form>
As you can see my XML file is simple the comments tag: http://jdrag.x10.mx/comments_file.xml
But when I submit the form I get this error:
Fatal error: Call to a member function addChild() on a non-object in /home/jdragx10/public_html/comments.php on line 5
And because i'm new to PHP I really don't know what it means or how to fix it.
Thanks in advance to anyone who can fix my code.
It looks like you want to be using simplexml_load_file().
The simplexml_load_string() function takes the XML document as a string whereas simplexml_load_file() takes the path to a file containing the XML, as you have.
You also have some problem with variable names, the path to the XML file is held in $date whereas you try to load the XML using the variable $data.
Finally, be sure to turn on (and to the maximum level) error reporting while you are writing your code. The code above gives a notice message ("Notice: Undefined variable: data…"), not just a fatal error message.
Set the values display_errors and error_reporting to On and -1 respectively, either in your php.ini file or using ini_set().

Categories