passes variable to table but cannot use it before - php

I got the following piece of code in php:
I have a page called post.php which posts successfully all data using jquery. The data that it posts are: $comments_id, $reply and $the_session_user_id as you can see in my code and I can get them successfully. My problem is that my equation if($session_user_id == $the_session_user_id ) is not working. It is like it cannot get $the_session_user_id. How can this be possible, since next it pass it to the table using the mysql statement? If I delete the if($session_user_id == $the_session_user_id ) and not make this choice, it passes succesfully all data to table. Any idea why my if statement not working?
<?php
// $session_user_id is the user id of the session
// the following data posted from a page called post.php wich posts them using jquery succesfully
$comments_id = $_POST['data_comments_id'];
$reply = $_POST['data_reply'];
$the_session_user_id = $_POST['data_session_user_id'];
if(isset($reply) && !empty($reply)){
if($session_user_id == $the_session_user_id ){
mysql_query("INSERT INTO comments_reply VALUES ('', '$comments_id', '$reply', now(), '', '$the_session_user_id') ");
}else{
mysql_query("INSERT INTO comments_reply VALUES ('', '$comments_id', '$reply', now(), '1', '$the_session_user_id') ");
}
}
?>

It doesn't seems like $session_user_id isn't declared/assigned any value. $session_user_id will therefore be 'null'. You must first assign your $_SESSION['your_id_key'] to $session_user_id: $session_user_id = $_SESSION['your_id_key']
You can try to echo both values ($session_user_id and $the_session_user_id) before the if to see wich value they've got assigned:
echo $session_user_id;
echo $the_session_user_id;

Related

Sending post to the database only works for the first submit

Updated - Code Formatting
I am trying to allow a user to submit a post. So far when a post is submitted it goes into the database with 'post' being empty. For some reason the text is not correctly going into the database but all the other information, such as id, date_added and added_by are correctly submitting. Also when submitting another post, it fails and I get the error, Could not create post. Here is the code:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
require_once('connect.inc.php');
$post = $_POST['POST'];
$date_added = date("y-m-d");
$added_by = "testuser";
$sql = "INSERT INTO IDEAS VALUES ('', '$post', '$date_added', '$added_by')";
if(mysqli_query($conn, $sql)){
echo "created";
}else{
echo "Could not create post";
}
mysqli_close($conn);
}
?>
Also, this is being used for an android app, how can I fetch the current user that is logged to be assigned to the variable $added_by? Do I call my login.php file in the beginning and use the username variable?

How to get a particular variable from another script

Can I fetch any variable (eg: username) from another script? Suppose there is a id which is in another table and I want to use as the 'id' field as foreign key in the new table. So how can I fetch it?
<?php
$submit=$_POST['submit'];
include_once('connection.php');
include_once('Home.php');
//Form Data
$id=mysql_query("SELECT id from users WHERE username='$username' ");
$pickup=strip_tags($_POST['pickup']);
$drop=strip_tags($_POST['drop']);
$time=strip_tags($_POST['time']);
$date=date("Y-m-d");
//$orderid =strip_tags($_POST['orderid']);
if($submit)
{ //check for existance
if($pickup && $drop && $time)
{
$queryreg = mysql_query("INSERT INTO ambu_book VALUES ('','$pickup','$drop','$time','$date','')");
}
else
{
echo "Please fill in all fields ! <p>";
}
}?>
Yes, you can use a variable from another php script if you do require() or include the script in the invocking script. But for how you did you wrote your question it seems you have an issue related to sql rather than php, i think.

php and mysql code

I have checked and rechecked my code for a tutorial that I am doing, and I still cannot figure out what is wrong with it. A bit of help would be appreciated.
I am building a page that processes the form data from another page. The part of the markup that I am having trouble with is below.
<pre>
if (isset($_POST['submit'])) {
// Process the form
$subject_id = $_GET["subject"];
$pageName = $_POST["pageName"];
$pagePosition = $_POST["pagePosition"];
$pageVisible = $_POST["pageVisible"];
$pageContent = $_POST["pageContent"];
if (!empty($errors)) {
$_SESSION["errors"] = $errors;
redirect_to("new_page.php");
}
$query = "INSERT INTO pages ( subject_id, menu_name, position, visible, content ) VALUES ('{$subject_id}' , {$pageName}, {$pagePosition} ,{$pageVisible} ,{$pageContent} )";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["message"] = "Page created.";
redirect_to("manage_content.php");
} else {
// Failure
$_SESSION["message"] = "Page creation failed.";
redirect_to("new_page.php?subject={$subject_id}");
}
</pre>
I have checked out the page that submits to the form processing page and the form submits correctly. I've also checked all the external functions that I reference and all of them work. Additionaly, the first variable that uses the $_GET superglobal works just fine. The problem is in the query somehow not being able to pull in the 4 $_POST variables. If I substitute all the variable values with hard-code values, the query goes through fine and creates a new row in my table.
Any help with this would be appreciated, as I have checked and rechecked this so many times, and I am sure I'm missing something very small, but it's driving me crazy.
Thanks.
You're missing quotes around your string values:
$query = "INSERT INTO pages ( subject_id, menu_name, position, visible, content ) VALUES ('{$subject_id}' , '{$pageName}', {$pagePosition} ,{$pageVisible} ,'{$pageContent}' )";
This would have been obvious if you checked for errors using mysqli_error().

Editing a form with PHP and MySQL: Best way to obtain an ID

I have a MYSQL table with edit and delete links on each row. The edit link goes to edit_patient.php which has a form (actually, a copy of the form originally used to insert patient into the database). After few tries, the script is working although I guess it could be improved (indeed, I get a notice of "Undefined index: id" when I submit the edits. The ID is passed to the edit_patient.php file through a GET procedure. Relevant code as follows:
// Check for a valid user ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_patient.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p>Sorry, it is not possible to update patient info at this time</p>';
include ('../elements/layouts/footer.php');
exit();
}
And, after some clean up and check on submitted values:
if($action['result'] != 'error'){
// Make the query:
$q = "UPDATE `demographics`
SET lastname='$lastname', firstname='$firstname', clinic='$clinic', sex='$sex', dob='$dob', age='$age',
disease_1='$disease_1', disease_2='$disease_2', disease_3='$disease_3', address='$address', city='$city', country='$country',
zip='$zip', phone_1='$phone_1', phone_2='$phone_2', phone_3='$phone_3', email_1='$email_1', email_2='$email_2',
physician='$physician', notes='$notes'
WHERE dem_id=$id
LIMIT 1";
$r = #mysqli_query ($db_connect, $q);
if (mysqli_affected_rows($db_connect) == 1) { // If it ran OK.
// Tell the user we have edited patient data successfully
$action['result'] = 'success';
array_push($text,'Patient data have been updated on databank');
}else{
$action['result'] = 'error';
array_push($text,'Patient data could not be changed on databank. Reason: ' .
'<p>' . mysqli_error($db_connect) . '<br /><br />Query: ' . $r . '</p>');
} // End of if (empty($errors)) IF.
} // End of if (empty rows))
Ok, so far so good. Now, in order to show already inserted data, I run another query:
// Retrieve the user's information:
$q = "SELECT lastname, firstname, clinic, sex, dob, age, disease_1, disease_2, disease_3, address, city, country, zip, phone_1,
phone_2, phone_3, email_1, email_2, physician, notes
FROM `demographics`
WHERE dem_id='".$_GET['id']."'";
$r = #mysqli_query ($db_connect, $q);
if (mysqli_num_rows($r) == 1) { // Valid user ID, show the form.
// Get the user's information:
$row = mysqli_fetch_assoc ($r);
// Create the form:
Here, the critical row I do not understand is WHERE dem_id='".$_GET['id']."'"; --> If I it leave as it is, the script runs almost Ok but then I get a notice of undefined index id.
However, when I replace with WHERE dem_id=$id"; as in the first query, the script gives a fatal error of undefined variable: id.
Finally, to submit the form I use the following command:
" /> that is working Ok, but it is not working when I use:
" />
Can anyone help me to understand why, and how to correct the issue, I'd rather prefer to be able to use simply $id (I believe is straight forward and simple) but for some reason is not working as expected. Finally, I would like to be able to report in the form to be edited also data inserted with radio buttons and drop-down (select) menus. Any advice on that would be greatly appreciated !
Please make sure that your specific record has been updated after the submit button in your edit_patient.php ? If it works and after next which page is display ..? Is it is Display.php (i.e. all record display page ) ? Please be specify first and i really help you to solve your query.

PHP Callback - Data not being inserted into DB

Ok so I have 3 files, coinbase.php, si.php (callback file), and profile.php.
Profile.php is what contains my CSS and HTML and the payment button. It also holds the custom parameter I need.
Si.php:
<?
require 'db.php';
$data = json_decode(file_get_contents('php://input'), TRUE);
$text = print_r($data,true);
file_put_contents('coinbase.php', $text);
$id = $data['order']['id'];
$status = $data['order']['status'];
$amount = $data['order']['total_btc']['cents'];
$user = $data['order']['custom'];
mysql_query("INSERT INTO `invoices`(`username`, `invoice_id`, `price_in_btc`) VALUES ('$user', '$id', '$amount')");
if($status == 'completed') {
mysql_query("UDPATE `users` SET `gigagold` = `gigagold` + '$amount' WHERE `username` = '$user'");
}
?>
And coinbase.php is the file that receives the decoded JSON data from the callback when a payment is made through the button. BUT, whenever something is in inserted into the DB all the values say NULL or are empty.
I don't see any problems with my code except I'm thinking my queries are in the wrong file?
Thanks.

Categories