I am trying to display the customer record from my database thats is determined by the id.
What I already have is a return where the id = 42. What I want to do is make it where the record returned is based on the id number that the user inputs on a previous page, which is $customerid. Any suggestions?
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
You can get the parameter passed to the PHP via GET or POST using $_GET["param_name"] and $_POST["param_name"] respectively.
So if your page is called using
http://path/to/page.php?id=99
You can get 99 in $_GET["id"]
Similar for POST.
Not having seen your form, I am assuming that you will POST the data.
Here is my suggestion for how to handle the data:
$id=isset($_POST['id'])&&is_numeric($_POST['id'])?$_POST['id']:false;
if ($id) {
$result = mysql_query("SELECT id,email FROM people WHERE id = $id;");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
} else {
echo "ERROR: No ID specified.";
}
Also, consider using PDO as mysql_* statements are depreciated. At the least, investigate how to prevent SQL Injection.
Try this:
search.php
<form action="show_record.php" method="post">
<input name="customer_id" />
</form>
show_record.php
<?php
// use $_REQUEST to get a parameter from POST OU GET request method
$id = isset($_REQUEST["customer_id"]) ? $_REQUEST["customer_id"] : 0;
$id = mysql_real_escape_string(); // prevent sql inject
$result = mysql_query("SELECT id,email FROM people WHERE id = '$id'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
So, you can request the page show_record.php from POST or GET, anyway the answer will be the same.
Via GET:
localhost/show_record.php?customer_id=42
Related
I'm having a problem getting a result from my mysql database and getting it to popular a form. Basically, i'm making an item database where players can submit item details from a game and view the database to get information for each item. I have everything working as far as adding the items to the database and viewing the database. Now i'm trying to code an edit item page. I've basically reused my form from the additem page so it is showing the same form. At the top of my edititem page, I have the php code to pull the item number from the url as the item numbers are unique. So i'm using a prepared statement to pull the item number, then trying to retrieve the rest of the information from the database, then setting each information to a variable. Something is going on with my code but I can't find any errors. I entered a few header calls to debug by putting information in the url bar...But the headers aren't even being called in certain spots and im not getting any errors.
In the form, I used things like
<input name="itemname" type="text" value="<?php $edit_itemname?>">
and nothing is showing in the textbox. I'm fairly new to php and it seems much more difficult to debug than the other languages i've worked with..Any help or suggestions as far as debugging would be greatly appreciated. I posted my php code below as well if you guys see anything wrong...I shouldn't be having issues this simple! I'm pulling my hair out lol.
Thanks guys!
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
}else{
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
}else{
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
}else{
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
header("Location: edititem.php?testing");
}
}
}
}
?>
To get the value of $edit_itemname into the output you should be using <?= not <?php. Saying <?php will run the code, so basically that is just a line with the variable in it. You are not telling it to print the value in the variable.
If your whole line looks like:
<input name="itemname" type="text" value="<?= $edit_itemname?>">
That should give you what you are looking for. The <?= is the equivalent of saying echo $edit_itemname;
If you don't like using <?= you could alternatively say
<input name="itemname" type="text" value="<?php echo $edit_itemname; ?>">
Your code should be change to a more readable form and you should add an output - I wouldn't recomment to use <?= - and you need to choose what you're going to do with your rows - maybe <input>, <table> - or something else?
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
} // no else needed -> exit()
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
} // no else needed -> exit()
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
} // no else needed -> exit()
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
// does not make sense here: header("Location: edititem.php?testing");
// show your data (need to edited):
echo "Name: " + $edit_itemname + "<br/>";
echo "Area: " + $edit_itemarea + "<br/>";
echo "Comment: " + $edit_itemcomments + "<br/>";
// end of current row
echo "<hr><br/>"
}
?>
I want to retrieve data from my SQL database and use it on my HTML page.
I have a php script get_score.php like this:
<?php
$con = mysqli_connect( "localhost", "xxx1", "xxx2", "xxx3");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `name`, `score` FROM crossstreet ORDER BY `score` DESC LIMIT 5";
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$output = ($row["name"]);
}
mysqli_free_result($result);
echo json_encode($result);
mysqli_close($con);
?>
And then I want to retrieve the data I via JQuery. I have read about the cross-origin issue but the data I retrieve and the html/Jquery are on the same server.
$.get("get_score.php", function( data ) {
console.log(window[data]);
}, "json" );
This returns undefined. If I make it $(data) it returns an object like the one on this screenshot.
Where is my mistake; how can I just get the data from the server to use in html?
You need to make $output an array so you get all the rows.
$output = array();
while ($row = mysqli_fetch_assoc($result)) {
$output[] = $row['name'];
}
Then you should echo this:
echo json_encode($output);
And in your jQuery code, you should do console.log(data);
mysqli_free_result($result);
echo json_encode($result);
i think this is the problem.
Try to reverse the order. You are making the result free before using it.
Do like this, instead of the above .
echo json_encode($result);
mysqli_free_result($result);
I have 2 PHP pages to delete employee data from table. For that, user inserts employee id, and press delete, to delete data from table.
Now, problem is, whenever I inserts id of one digit(2,3,8 etc), id is not deleted. However, if two digit id is inserted (12,19,99 etc), it gets deleted.
Please help me to solve where I am wrong.
Here is my code for first PHP page:
<form action="deleteemp.php" method="post" onSubmit="return confirm('Are you sure to delete?')">
Enter id to delete data<input type="text" name="EmpId" required>
<button type="submit" >Delete</button>
</form>
Here is my action PHP page,
<?php
$EmpId = $_POST['EmpId'];
$connection = mysql_connect("localhost", "root", "");
if (!$connection) {
die("Connection failed " . mysql_error());
}
$db_conn = mysql_select_db("hms", $connection);
if (!$db_conn) {
die("Connection failed " . mysql_error());
}
$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;
$db_result = mysql_query($query, $connection);
if ($db_result) {
echo "Data Deleted Successfully !";
echo "<br>";
echo "<a href='homepage.php'>Back to homepage</a>";
} else {
echo "Data Not there. Try Again !<br>";
echo "<a href='deleteemp1.php'>Search again</a>";
}
echo "data not here" is incorrect. mysql_query returns boolean false on FAILURE. An empty result (no matching IDs) is NOT a failure. It's a successful query which happens to have an empty result set.
Your code should be more like
$result = mysql_query($query) or die(mysql_error());
if (mysql_affected_rows($result) == 0) {
die("No rows deleted");
}
And note that you are vulnerable to sql injection attacks, and using an obsolete/deprecated DB library.
Try this
$query = "DELETE FROM employee_details WHERE emp_id = '$EmpId'";
$db_result = mysql_query($query, $connection);
if ($db_result)
{
echo "Data Deleted Successfully !";
echo "<br>";
echo "<a href='homepage.php'>Back to homepage</a>";
}
else
{
echo "Data Not there. Try Again !<br>";
echo "<a href='deleteemp1.php'>Search again</a>";
}
This seems some exceptional issue, so try typecasting before passing value to SQL query.
Try using this for assigning value to $EmpId:
$EmpId = (int) $_POST['EmpId'];
can you try to change below code from
$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;
TO
$query = "DELETE FROM employee_details WHERE emp_id =".$EmpId;
Just try. This might work for you
Trying to use ComboBox populated from mysql to send the $id to a second page to be used in a query to populate data.
Here is my code sitting in the bootsrap nav bar on page 1
<form class="navbar-form navbar-left" action='customerpage.php' method='post'>
<div class="form-group">
<select type="submit" id="navbarcustomer" class="form-control" name='customerid' placeholder="Customer Lookup">
<option>Customer Lookup</option>
<?php
require ('dbconnect.php');
$result = $con->query("select id, lastname, firstname from customer");
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$name = $row['lastname'];
$firstname = $row['firstname'];
echo '<option value="/customerpage.php?id='.$id.'">'.$name.','.$firstname.'</option>';
}
echo "</select>";
mysqli_close($con);
?>
</div>
</form>
here is my code on page to that needs to receive the $id variable to be used in the query
<?php
$id = $_GET['custid'];
echo $id;
require ('dbconnect.php');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM customer WHERE id=' . $id . '");
//$result = mysqli_query($con,"SELECT * FROM customer WHERE id=$id");
while($row = mysqli_fetch_array($result)) {
echo $row['firstname'];
echo "<br>";
}
?>
Please help the name of page 2 is /customerpage.php Thank you.
It looks like you've set it up so that when you click the dropdown, it will automatically go to the customers page. We will need just a little bit of JavaScript for that.
Place this below your closing </form> tag, but preferably right before you closing </body> tag document.
<script>
var navbarcustomer = document.getElementById('navbarcustomer');
navbarcustomer.addEventListener('change', function (e) {
window.location = this.value;
});
</script>
If you're using jQuery, you can OPTIONALLY use this in your <script> tags instead of the code above:
$('#navbarcustomer').on('change', function () {
window.location = $(this).val();
});
Next, you need to make sure your GET vars match what you're sending it. Change $_GET variable to look like this, as you are providing id= in the query string (and not custid=):
$id = $_GET['id'];
Edit:
There are a few more things that need to be addressed. Also in the customerpage.php, your query is little broken. You can use something like to fetch your records, it's a little bit cleaner:
$id = (int) $id; // cast to integer to prevent SQL injection.
$result = $con->query("SELECT * FROM customer WHERE id = $id");
// there is only going to be 1 record so we don't need the while loop.
$row = $result->fetch_assoc();
echo $row['firstname'];
echo $row['lastname'];
<?php
include 'config.php'; //connect to db
if(isset($_REQUEST["pwd"]) && isset($_REQUEST["name"])) {
$password = $_REQUEST['pwd']; //pass from previous page
$name = $_REQUEST['name']; //pass from previous page
$checkUserPass = mysql_query("SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //check if the user exist
if(mysql_num_rows($checkUserPass) == 1) {
$personnelId = mysql_query("SELECT PersonnelID FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //query user id
while($row = mysql_fetch_assoc($personnelId)) {
echo $row['PersonnelD']; // print user id
}
mysql_close($conn);
//echo "<br/><br/>";
//echo "<script>alert('Logged In.')</script>";
//header("Refresh: 1; url=profile/profile.php?id="'.$id.');
//header('Refresh: 1; url=test.php?id=$personnelId');
} else {
echo "<br/><br/>";
echo "<script>alert('Wrong Password.')</script>";
header('Refresh: 1; url=personnelselect.php');
}
}
?>
i cannot echo the $row['PersonnelD'] the page shows blank. i cannot understand where did i go wrong. this page quesion have been solved
Looks like you have mistake in code:
echo $row['PersonnelD'];
shouldn't it be following?
echo $row['PersonnelID'];
check the mysql_fetch_assoc() function may be its parameter is empty so it can't enter the while loop
Try to debug and check the values came in the variables using var_dump() function. Ex: var_dump($row); in while loop.
In both your querys, you have
"SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'"
It should be:
"SELECT * FROM validPersonnel WHERE Passkey = '".$password."' and Name = '".$name."';"
PHP doesn't recognize the $var unless you close the quotes. The period adds the $var to the string.