Pass PHP fetch variable to another page - php

I have a form that submits to firstpage.php, this page includes the code to insert all form values into the database and check for duplicate entries, if the entry is a duplicate , display the duplicate entry using the following php code
$checkstudentID = mysqli_query
($dbcon, "SELECT studentid from courses WHERE studentid = '$studentid'");
if(mysqli_num_rows($checkstudentID) > 0){
if ($stmt = mysqli_prepare($dbcon, "SELECT ckb from courses WHERE studentid = ?")) {
mysqli_stmt_bind_param($stmt,"s",$studentid);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $ckb);
mysqli_stmt_fetch($stmt);
printf("<br /><center><h1>Your Student ID is</h1> <h2>%s.</h2><h1> Subjects Registered : %s\n </h1>", $studentid, $ckb );
mysqli_stmt_close($stmt);
}
mysqli_close($dbcon);
die(" <p> The Student ID <strong>$studentid </strong>already exists. Update</p>");
the page update.html includes an update form that submits to update.php
how can I pass the the single fetched row variable (subjects registered/$ckb) to update.html ?
I tried the following so far:
at the firstpage.php I started a session
session_start();
$_SESSION['subjects'] = '$ckb';
and at the update.html > renamed to update2.php and added the following at the top of the page
<?php
session_start();
echo $_SESSION['sujects'];
?>
and at the input field the value="<?php echo $ckb;?>"
What am I missing ?
Please note, that the variable I want to pass is the subjects registered related to the student id checked in firstpage.php file meaning this :
printf("<br /><center><h1>Your Student ID is</h1> <h2>%s.</h2><h1> Subjects Registered : **%s**\n </h1>", $studentid, $ckb );
but its either completely wrong or I'm just passing the wrong variable

Remove quotes in:
$_SESSION['subjects'] = '$ckb';
So it will be:
$_SESSION['subjects'] = $ckb;
And update 2nd file to this:
<?php
session_start();
$ckb = $_SESSION['subjects'];
?>
....
<input type='text' value="<?php echo $ckb;?>" />
Note: also, you wrote sujects in second file, its ok in my code example.

In answer to my question I found an easy and effective by passing the variables through the url.
Meaning...
In my firstpage.php, the href links to my update2.php page became as follows:
Update
The $studentid and $cc variables are previously defined in my code where I "get" them from the input fields of the form.
In update2.php, the page which I would like to pass the variables to I inserted the following code
<?php
$studentid= $_GET['studentid'];
$cc = $_GET['ckb'];
?>
Which allowed me to use the variables throughout the rest of the php code, where for my case I wanted them to be the "values" of a new form input field, as shown below :
<input name="newcourses" type="text" id="newcourses" maxlength="70" value="<?php echo $cc?>"" />
I recommend anyone who wants a more clear idea and read more about other methods to pass variables across php pages to check this out >> Pass PHP fetch variable...

Related

$_POST is removing a single quote (OR how to get a single quote into a $_POST) [duplicate]

This question already has answers here:
Escape double quotes with variable inside HTML echo [duplicate]
(3 answers)
Closed 1 year ago.
First want to start off by saying that I am still a beginner developer but have gotten a long way in a short time and I am somewhat stumped. And yes I know my code might not be pretty in layout, but still learning, at least things are working.
I am creating something that is like a client portal for shows. A client signs up to do a show from an intake form. When they submit the form, it goes to Monday.com, creates a folder and sub folder in dropbox and then inserts everything into my Mysql database. I also then have another page (Assets) where they can upload files based on the show. Now if they have signed up for multiple shows, at the top of this page I have a dropdown box that grabs all the shows that is assigned to their used id. When they click on the show that they want to add files to and then click the "Choose Show For Asset Upload" button it goes back to the database to retrieve the dropbox path and the file request url and puts it into the code where those variables are assigned. So, everything is working great except when it comes to a show that has a single quote (apostrophe). I noticed this when I added a test show and everything went bonkers. I was able to figure everything out when it comes to making it correct in the code for Monday and Dropbox and even INSERTing it into the database. In the database column it has "Michael's" instead of "Michael\'s", so it's exactly how it should be in there. In the dropdown it actually shows "Michael's" but yet when I do an echo after clicking the button it shows "Michael" So that single quote is definitely the issue and this is where I don't know how to fix it, after much searching through the net.
In the dropdown it lists (Show Test, Did I Really Do It!!, Dudley, The Amazing MA, Lets See If This Works, Michael's).
Code is:
<div class="topdiv">
<h2 style="text-align: center;">Assets Upload</h2><br>
</div>
<?php
$userid = $_SESSION["userid"];
$sql = "SELECT * FROM intake WHERE userid = ?;";
$stmt = mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "There was an internal error!";
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $userid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
?>
<form class="formcenter" action="assets.php" method="post">
<select name="show" id="show">
<?php
while ($rows = mysqli_fetch_assoc($result)) {
$show = $rows['showtitle'];
echo "<option value='$show'>$show</option>";
}
?>
</select>
<input type="submit" name="chooseShow" value="Choose Show For Asset Upload"><br><br>
</form>
<?php
if(isset($_POST["chooseShow"])) {
$showTitle = $_POST["show"]; //WHEN I DO AN ECHO OF THIS IT SHOWS "MICHAEL" NOT "MICHAEL'S"
$sql = "SELECT * FROM intake WHERE userid = ? and showtitle = ? ;";
$stmt = mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "There was an internal error!";
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $userid, $showTitle);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rows = mysqli_fetch_assoc($result);
$path = $rows['dbxPath'];
$requestURL = $rows['requestURL'];
echo $show; //THERE JUST TO SEE WHAT IT WAS OUTPUTTING
echo $showTitle; //THERE JUST TO SEE WHAT WAS OUTPUTTING
}
}
?>
When I do the two echos at the end of the code $show = "Michael's" and $showTitle = "Michael". So I do know that the correct way is coming through but just can't grab it to put in the last $sql variable to use as the $showTitle Granted, I am assuming the $show is showing "Michael's" because it's the last show in the loop. BUT when I tested $show instead of $showTitle in the mysqli_stmt_bind_param statement it actually worked, so I know it's possible. Just need to know how to get the full "Michael's" into my $showTitle variable.
Thank you for taking the time to look through this longwinded (trying to give you as much info as possible) question and appreciate any help and advice.
-Michael
Your problem is here:
echo "<option value='$show'>$show</option>";
The single quotes in the variable $show are interfering with the single quotes wrapping the value.
Change it to this:
echo '<option value="'.$show.'">'.$show."</option>";
This explicitly concatenates the parts of the string rather than interpolating it. It gives better control over what quotes are used and where.

Pass foreign key via $_GET

I have an online courses CRUD application. It has, among other pages, an instructor BIO page.
First, the instructors are added, in an users table, with basic data: first_name, last_name, and email; then a BIO can be added, optionally, for any instructor. There is a second database table, called "bios", to serve this purpose.
I need to pass $user_id into the courses table, (as foreign KEY) an for that purpose i use $_GET:
<?php
$user_id = $_GET['id'];
if(isset($_POST['submit-btn'])) {
$no_courses = $_POST['no_courses'];
$years_exp = $_POST['years_exp'];
$fav_lang = $_POST['fav_lang'];
$courses = $_POST['courses'];
$sql = "INSERT INTO courses (user_id, no_courses, years_exp, fav_lang, courses) VALUES ('$user_id', '$no_courses', '$years_exp', '$fav_lang', '$courses')";
if (mysqli_query($con, $sql)) {
echo("<p>Instructor bio was added.</p>");
} else {
echo "Error: " . mysqli_error($con);
}
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="add_bio">
...
</form>
Using $_GET seems convenient because in a table with a lot of rows, containing instructors, on the right most cell/column, I have a set of link buttons for CRUD operations, "Add bio" being one of those buttons.
<a title="Add bio" href="add_bio.php?id=<?php echo $arr['id']?>"><span class="glyphicon glyphicon-plus-sign"></span></a>`
But instead of passing the $user_id variable so that the bio can be added, the server throws these errors:
Notice: Undefined index: id in E:\xampp\htdocs\courses\add_bio.php on line 7
Error: Cannot add or update a child row: a foreign key constraint fails
How can I pass the user's id if I want to keep the CRUD links mentioned above?
Thank you!
You may have some issues with the content being submitted.
A great troubleshooting approach would be to:
print_r($_GET);
or
print_r($_POST);
Another option is to also:
echo print_r($_GET, true);
The Second argument (True) tells the print_r function to return as a string instead of output to the browser.
Review that output and verify you are actually getting an "ID" value in your GET and POST variables.
Also, some security concerns, any data you take in from GET or POST or REQUEST or COOKIE should be "cleaned" you can look at:
mysqli_real_escape_string
Additionally, Never use PHP_SELF. In almost all cases, it can be manipulated to execute a Cross Site Scripting Attack, and that is bad news. if you want to submit the form to the current script, you can leave the "action" attribute as an empty string.
action=""
Hope this helps!!!
The form was missing this line, right above the submit button:
<input type="hidden" name="id" value="<?php $user_id;?>">

PHP HTML SQL Passing Parameters to Update Database [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 months ago.
I am very new to the subject of PHP and SQL working together and I have been fine so far except for updating a database row on my SQL database. I'm using parts of my lecturers code and doing exercises and my own tasks to modify the webpages and behaviour.
The process of this code is to update an article that I have set up, so I can edit the title or the code then click confirm but when I do this I get my failed return message telling me there is a parameter problem. I have often had trouble passing parameters in other languages and I have been looking and testing this for a few hours that I am hoping to receive some information and guidance on the subject.
All I want to do is update the articletext and articletitle fields.
My EDIT ARTICLE code section:
<?php
$db=createConnection();
// get the first two articles
$sql = "select blogID,articletitle,articletext,blogtime,blogposter,username,userid from blogarticle join registerdemo on blogposter = userid where blogID=?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i",$article);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($articleid,$articletitle,$articletext,$blogtime,$blogposter,$username,$userid);
//build article html
while($stmt->fetch()) {
echo "<article id='a$articleid'>
<h1>$articletitle</h1>
<p>".nl2br($articletext)."</p>
<footer><p>Posted on <time datetime='$blogtime'>$blogtime</time> by <em>$username</em></p></footer>";
// if user is logged in and not suspended add comment button
if($currentuser['userlevel']>2 || ($currentuser['userid']==$userid && $currentuser['userlevel']>1)) {
?> <form method='post' action='applychanges.php'>
<input type="text" name="articletitle" id="articletitle" size="30" required value="<?php echo $articletitle; ?>"/><br />
<textarea name="articletext" id="articletext" cols="60" rows="5"><?php echo $articletext; ?></textarea></br>
<button type="submit">Confirm</button>
</form>
<?php
}
echo "</article>";
}
$stmt->close();
$db->close();
?>
My APPLY CHANGES code:
This is where the parameters fail
<!doctype html>
<html lang="en-gb" dir="ltr">
<head>
</head>
<body>
<?php
include('php/functions.php');
if(isset($_POST['articleid']) && isset($_POST['articletitle']) && isset($_POST['articletext'])) {
$db=createConnection();
$articleid=$_POST['articleid'];
$articletitle=$_POST['articletitle'];
$articletext=$_POST['articletext'];
$updatesql="UPDATE blogarticle SET articletitle='$articletitle', articletext='$articletext' WHERE articleid='$articleid'";
$doupdate=$db->prepare($updatesql);
$doupdate->bind_param("ssi",$articletitle,$articletext,$articleid);
$doupdate->execute();
$doupdate->close();
$db->close();
header("location: index.php");
} else {
echo "<p>Some parameters are missing, cannot update database</p>";
print_r($_POST);
}
?>
</body>
</html>
Result:
Some parameters are missing, cannot update database
Array ( [articletitle] => THIS IS A TEST [articletext] => hey )
You are not posting all the parameters with your form. For example, the textarea is missing the name attribute. This will result in not posting this form field your script. Add the following line to your "Apply changes" code. This will print out the parameters you are posting.
print_r($_POST);
Check which parameters are not posted.
You probably want to add some hidden form fields.
The Update query needs to include the data variable names . Query needs to be as follows:
$updatesql="UPDATE blogarticle SET
articletitle='$articletitle', articletext='$articletext' WHERE articleid='$articleid'";

Insert data / update if already exists

This code works. I can't figure out how to insert data into db If user pressed "SAVE" button for the first time or update data.
The php side
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')") or die($db->error);
if ($new_id>0){
echo "{";
echo '"msg": "success" ';
echo "}";
}else{
echo "{";
echo
'"err": "error"';
echo "}";
}
?>
UPDATE
Thanks to #jmlsteeke i found the way
Place this piece of code in html part
<?php
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('555', 'new', '0')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', 'new', 'new')") or die($db->error);
?>
And added following code into form
<input type="hidden" name="id" value="<?=$new_id?>"/>
In serverside script used
$result=$db->query("UPDATE pages AS p, menu AS m SET m.parent='$parent', m.name='$name', m.showinmenu='$menu', p.id='$id', p.title='$title', p.content='$content' WHERE m.id='$id' AND p.id=m.id") or die($db->error);
Thank you #jmlsteeke
A common way would be to store the id as a hidden field when you are editing the page. This way when the user submits the page, if there is an id present, you issue the UPDATE commands, and if there isn't one present, you know it's a new page, and issue the INSERT commands.
If you need me to be more thorough let me know.
Edit: Being More Thorough
I'll make a simple, complete, example of what I mean.
Form.php pseudo code
//set default values for fields
//print form tag
if (isset($'id',$_GET)) {
//fetch data from database
//print hidden id field
//override default values for fields
}
//print rest of fields using default values (possibly overridden)
DoForm.php pseudo code
//Sanitize user input
if (isset('id',$_POST)) {
//UPDATE database with user input
} else {
//INSERT new rows into table with user input
}
Let's say you have a php file called Form.php which is responsible for displaying the form, and another php script called DoForm.php which is responsible for handling the form.
If a user visits Form.php with no ID specified (http://example.com/Form.php) then it will display the following form:
<form method="post" action="DoForm.php">
<input type="text" name="name" value="" />
<input type="text" name="title" value="" />
... other stuff ...
</form>
The user will add some information, click on the submit button and DoForm will get the following POST variables:
"name" => "NewPageName"
"title" => "My First Webpag" [intetional typo, see later]
... other stuff ...
DoForm will check to see if $_POST['id'] exists. Since it doesn't DoForm issues the INSERT commands to add a new page.
Later on, the user realises the made a typo, and goes to fix it. The user clicks on the "Edit Page" control for "NewPageName" which will be http://example.com/Form.php?id=1
Form.php see's that id is set, so the form it prints out is as follows:
<form method="post" action="DoForm.php">
<input type="hidden" name="id" value="1"
<input type="text" name="name" value="NewPageName" />
<input type="text" name="title" value="My First Webpag" />
... other stuff ...
</form>
The user fixes their type, changing Webpag to Webpage, and hits submit. DoForm gets the following Post variables
"id" => 1
"name" => "NewPageName"
"title" => "My First Webpage"
... other stuff ...
DoForm sees that id is set, and so uses UPDATE instead of INSERT.
Any more clear?
MySQL has an INSERT ... ON DUPLICATE KEY UPDATE feature that will let you try to insert a row, or fall back to an update if it discovers a duplicate key (i.e. the row already exists).

Editting data by ADMIN

I am new to PHP and working on small local webpage and database that takes user information and database stores the same user information .If i Login with ADMIN it shows all data. My requirement is that the loggined user is an admin, then he has a right to edit all the informtion of the users that i stored in the database.And this is to be done using GET method . How it will be working?
Heres some example code purely to demonstrate how to update a table using a GET method form. The code doesn't have any kind of error checking and assumes you already know how to connect to your database (and that its MySQL).
Assuming you've landed on a page which invites you to edit data, which record you're editing is referenced by an 'id' variable on the URL which matches a numerical primary key in your database table.
<?php
$SQL = "SELECT myField1,myField2 FROM myTable WHERE myKeyField = '".intval($_GET['id'])."'";
$QRY = mysql_query($SQL);
$DATA = mysql_fetch_assoc($QRY);
?>
<form method='get' action='pageThatStoresData.php'>
<input type='hidden' name='key' value='<?php echo $_GET['id']; ?>' />
<input type='text' name='myField1' value="<?php echo $DATA['myField1']; ?>" />
<input type='text' name='myField2' value="<?php echo $DATA['myField2']; ?>" />
<button type='submit'>Submit</button>
</form>
So, this will give you a page that takes the data out of your table, displays it in a form with pre-filled values and on submit, will go to a URL like:
http://mydomain.com/pageThatStoresData.php?key=1&myField1=someData&myField2=someMoreData
In that page, you can access variables 'key', 'myField1', 'myField2' via the $_GET method.
Then you just need to update your table within that page:
$SQL = "UPDATE myTable
SET myField1 = '".mysql_real_escape_string($_GET['myField1'])."',
myField2 = ".mysql_real_escape_string($_GET['myField1'])."
WHERE key = '".intval($_GET['key'])."'
";
$QRY = mysql_query($SQL);
PLEASE NOTE: The code above is unsuitable for a straight copy/paste as it doesn't do any error checking etc, its purely a functional example (and typed straight in here so I apologise if there are any typos!).

Categories