I have an interface below
When I click the edit button (icon pencil), the form bellow will appear
The edit button has a code below in php file :
$elisting ="";
$queryf = "select employee.id as myid,jobtitle,info,locid,deptid,gender,dob,emid,employee$cid.name,username,dept,datejoin,location.name as loc from employee
left join location on location$cid.id = employee.locid
inner join department on department.id = employee.deptid order by username
";
$resultf = pg_query($queryf);
$numrows = pg_numrows($resultf);
while ($rowf = pg_fetch_array($resultf)) {
$ct=$ct+1;
$myid = $rowf[myid];
$uname = $rowf[username];
$loc1 = $rowf[loc];
$dept = $rowf[dept];
$date = $rowf[datejoin];
$name = $rowf[name];
$emid = $rowf[emid];
$dob = $rowf[dob];
$gender = $rowf[gender];
$job = $rowf[jobtitle];
$info = $rowf[info];
$datejoin = $rowf[datejoin];
$locid = $rowf[locid];
$deptid = $rowf[deptid];
$newbal = $rowf[newbal];
$templatelist = "";
$tempcn = 0;
$querytemp = "select tid,ltype from leaveatemplate$cid where username='$uname' order by tid desc";
$resulttemp = pg_query($querytemp);
while ($rowtemp = pg_fetch_array($resulttemp)) {
$tempcn = $tempcn +1;
$tid = $rowtemp[tid];
$ltype = $rowtemp[ltype];
if($tempcn=="1")
$templatelist = "$ltype|$tid";
else
$templatelist = $templatelist.","."$ltype|$tid";
}
$elisting=$elisting."<tr><td align=\"center\">$uname</td><td align=\"center\">$loc1</td><td align=\"center\">$dept</td><td align=\"center\">$date</td><td align=\"center\"><button class=\"btn btn-mini\"data-toggle=\"modal\"href=\"#long\"
onClick=\"javascript:edit('$name','$uname','$emid','$dob','$gender','$job','$info','$datejoin','$locid','$deptid','$myid','$templatelist', '$value');\"><i class=\"icon-pencil\"></i></a><button class=\"btn btn-mini\" data-toggle=\"modal\" href=\"#static\" rel=\"tooltip\" data-original-title=\"Delete\" onClick=\"javascript:delrec('$myid');\"><i class=\"icon-remove\"></i></a></td>
</tr>\n";
}
I wonder how can the code select the right data as the button clicked? Because I saw there is no requirement in the query, for example where id = 123 or something like that. When choose adam, the adam's data will appear. Anyone can explain this?
UPDATE:
function edit(a,b,c,d,e,f,g,h,i,j,k,l){
document.getElementById("frm").id.value=k;
document.getElementById("frm").name.value=a;
document.getElementById("frm").username.value=b;
document.getElementById("frm").emid.value=c;
document.getElementById("frm").dob.value=d;
setCheckedValue(document.forms['frm'].elements['gender'],e);
document.getElementById("frm").job.value=f;
document.getElementById("frm").info.value=g;
document.getElementById("frm").datejoin.value=h;
document.getElementById('locid').value=i;
document.getElementById('deptid').value=j;
}
This line explain everything:
onClick=\"javascript:edit('$name','$uname','$emid','$dob','$gender','$job','$info','$datejoin','$locid','$deptid','$myid','$templatelist', '$value');
As you can see in the javascript edit function the id of the object ($myid i guess) is passed along with all the other properties of the object.
Related
I want to update multiple authors but when i click the update button it saves last inputted value on all of the fields. Your response is highly appreciated. Thank you so much!!!
Here is my code
<?php
}elseif($ID[0]=="Update"){
$Author_Query = mysql_query("SELECT a.*, b.* FROM tblAuthor a, tblResources b WHERE a.Accession_No = b.Accession_No AND a.Accession_No = '".$ID[1]."'");
while($Author = mysql_fetch_array($Author_Query)){
?>
<td><input type="text" name="Author[]" value="<?php echo $_POST['Author']; ?><?php echo $Author['Author']; ?>" /></td>
<?php }} ?>
Update button code
if($_POST['Update'] == "Update"){
$Ac1 = $_POST['Accession1'];
$Ac2 = $_POST['Accession2'];
do{
mysql_query("UPDATE tblResources SET
Accession_No = '".$Ac1."',
Month = '".$_POST['Month']."',
Day = '".$_POST['Day']."',
RYear = '".$_POST['RYear']."',
Class = '".$_POST['Class']."',
Title = '".$_POST['Title']."',
Edition = '".$_POST['Edition']."',
Volumes = '".$_POST['Volumes']."',
Pages = '".$_POST['Pages']."',
Source_of_Fund = '".$_POST['Source_of_Fund']."',
Cost_Price = '".$_POST['Cost_Price']."',
Publisher = '".$_POST['Publisher']."',
Year = '".$_POST['Year']."',
Remarks = '".$_POST['Remarks']."',
Category_ID = '".$_POST['Category']."',
Type_ID = '".$_POST['ResType']."',
Copies = '1',
Availability = '".$_POST['Availability']."',
Tag = 'Title',
Year_Level = '".$_POST['Year_Level']."'
WHERE
Accession_No = '".$Ac1."'");
//$q = $Text."/";
//$gets = explode("/",$q);
$Get = $_POST['Author'];
$Box = count($Get);
for($Text = 0; $Text < $Box; $Text++){
$TextBox = $Get[$Text];
mysql_query("UPDATE tblAuthor
SET Author = '".$TextBox."'
WHERE Accession_No = '".$Ac1."'");
}
$Ac1++;
}while($Ac1 <= $Ac2);
echo "<script language=javascript>
alert('Successfully Updated!');
location.href='Resources.php';
</script>";
}
The problem happen because field 'Accession_No' it's same for author, so the effective update always the last one.
I think something like this solve your problem:
$Get = $_POST['Author'];
$Box = count($Get);
if($Box > 0) {
mysql_query("DELETE FROM tblAuthor WHERE Accession_No = '".$Ac1."'");
foreach($Get as $author){
mysql_query("INSERT INTO tblAuthor (Author, Accession_No) VALUES ('".$author."', ".$Ac1.");
}
}
It's necessary remove the author, because if one author isn't in table before, the mysql not update, the record doesn't exists. So, it's easy remove all authors and insert again.
When you go from the previous page to the current page it will autmatically fill a div with a specific mysql query result, the only issue is that when the page it initially loads it displays the previous query result, you have to refresh the page to get the current result and I dont understand why.
In my php at the top of the page I call a function from another page. This functin checks my database for a specific result and returns it, that result is then echo'd into a div class.
<--index.php-->
<?php
require_once(__DIR__.'/myFunctions.php');
$desc = returnDesc();
?>
...
...
<body>
<div class = "descBox">
<?php echo $desc; ?>
</div>
</body>
and the function itself is..
<--myFunctions.php-->
function returnDesc()
{
$con = connection();
$planetMoon = (mysqli_query($con, "SELECT Sol, Star, Planet, Moon FROM MK1 WHERE id = 1"));
if ($planetMoon->num_rows > 0) {
while ($row = $planetMoon->fetch_assoc()) {
$descSol = $row["Sol"];
$descStar = $row["Star"];
$descPlanet = $row["Planet"];
$descMoon = $row["Moon"];
$Desc = (mysqli_query($con, "SELECT Description FROM DescBox WHERE Sol = '$descSol' AND Star = '$descStar' AND Planet = '$descPlanet' AND Moon = '$descMoon'"));
if ($Desc->num_rows > 0) {
while ($row = $Desc->fetch_assoc()) {
return $descPlanetMoon = $row["Description"];
}
}
}
}
mysqli_close($con);
}
Change to:
function returnDesc()
{
$con = connection();
$descPlanetMoon = array();
$planetMoon = (mysqli_query($con, "SELECT Sol, Star, Planet, Moon FROM MK1 WHERE id = 1"));
if ($planetMoon->num_rows > 0) {
while ($row = $planetMoon->fetch_assoc()) {
$descSol = $row["Sol"];
$descStar = $row["Star"];
$descPlanet = $row["Planet"];
$descMoon = $row["Moon"];
$Desc = (mysqli_query($con, "SELECT Description FROM DescBox WHERE Sol = '$descSol' AND Star = '$descStar' AND Planet = '$descPlanet' AND Moon = '$descMoon'"));
if ($Desc->num_rows > 0) {
while ($row = $Desc->fetch_assoc()) {
$descPlanetMoon[] += $row["Description"];
}
}
}
}
mysqli_close($con);
return $descPlanetMoon;
}
I have a search function on my website with 4 checkboxes. These are then pasted to the next page where I want to find all products which match the criteria of the check boxes.
As I have 4 check boxes I want to use 4 'ands' but I believe 3 is the max (?)
How can I get around this so it searches to see if all products are matched?
HTML Form
<div id = "search">
<form name = search action = "search.php" method = "POST">
<p class = "big"> Refine Menu </p>
<hr>
<input type = "text" name = "search" placeholder = "Search for an item" size = "12">
<input type = "submit" value = "Go">
<br><br>
<input type = "checkbox" name = "vegetarian"> Vegetarian
<br><input type = "checkbox" name = "vegan"> Vegan
<br><input type = "checkbox" name = "coeliac"> Coeliac
<br><input type = "checkbox" name = "nutFree"> Nut free
</form>
</div>
PHP
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = NULL;
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = NULL;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = NULL;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = NULL;
}
$sql = "SELECT * FROM products WHERE vegan = '$vegan' and nutFree = '$nutFree' and vegetarian = '$vegetarian' and coeliac = '$coeliac'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
I've tried a number of different thing but I don't know the correct syntax for the sql.
NOTE: In my database whether it meets the requierment on it is saved as either a 1 or 0 that is why I changed it from 'on' or 'off'
Rather than a large, unmaintainable chain of if statements, you might consider something similar to the following, which will dynamically build up your query depending on which of your required fields have been checked in your form:
<?php
$search_fields = array( 'vegetarian', 'vegan', 'nutFree', 'coeliac', ...);
$ands = array( '1' => '1');
foreach($search_fields as $req)
{
if(isset($_POST[$req]) && $_POST[$req] != '')
{
$ands[$req] = "$req = '1'";
}
}
$and_part = implode(" AND ", $ands);
$query = "select .... from ... WHERE $and_part ... ";
?>
I managed to solve my problem. I was mistaken when I posted the question because the reason I thought my sql statement wasn't working was because there were too many ands and I didn't see that rather my sql didn't do what I thought it should.
Here is what I changed it to or it has set values or the check boxes ticked but always the ones which aren't to be either or.
Thanks for everyone's help!
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = " ";
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = " " ;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = " " ;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = " ";
}
$sql = "SELECT * FROM products WHERE (vegan = '$vegan' or vegan = 1 xor 0) and (nutFree = '$nutFree' or nutFree = 1 xor 0) and (vegetarian = '$vegetarian' or vegetarian = 1 xor 0) and (coeliac = '$coeliac' or coeliac = 1 xor 0)";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
PHP's NULL have no significance when converted to a string (the SQL query), they will evaluate to empty and your query will look like nutFree = '' and vegetarian = '' and coeliac = ''.
If those fields are 0 in the database, you must set the variables to 0 then.
On a second case, if they are NULL in the database, you must change both your query and the way you define NULL here.
First, those string wrappers should go away. You don't need them for numbers anyway, those are supposed to wrap strings only:
$sql = "SELECT * FROM products WHERE vegan = $vegan and nutFree = $nutFree and vegetarian = $vegetarian and coeliac = $coeliac";
And then instead of setting the variables to NULL, you will set them to the string "NULL".
$nutFree = "NULL";
This will make NULL show on the SQL query as its expected to.
I am having a problem when I want to echo "The stock is less than what you want". The problem is the user still can update the cart when the stock in my database less that what the user wants. It should show an error "The stock is less than what you want".
This is my code.
<?php session_start();
require("config.php");
$user = $_SESSION['userlogin'];
$cek = mysql_query("SELECT * FROM transaksitbl WHERE username = '$user' AND status ='0'") or die(mysql_error());
$result = mysql_num_rows($cek);
$data = mysql_fetch_array($cek);
if ($result > 0)
{
$faktur =$data['notransaksi'];
for ($i=1; $i<=$_POST['n']; $i++)
{
$idp = $_POST['id'.$i];
$cari2 = mysql_query("SELECT * FROM barangtbl WHERE id='$idp'") or die(mysql_error());
$row2 = mysql_fetch_array($cari2);
$har = $row2['harga'];
$stock = $row2['stock'];
if($_POST['n'] <= $row2['stock'])
{
echo "The stock is less than what you want";
}
if ($cari2)
{
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
}
}
}
header ("location:shopping_cart.php");
?>
If i understood you properly the
if($cari2){}
function is executing?
All you are checking there is if the $cari2 variable is true.
Simply make a else statement out of the if($cari2){} statement so that if the stock is less than you wan't the second if statement won't get executed.
So, like this:
if($_POST['n'] <= $row2['stock']){
echo "The stock is less than you want";
}
else {
if($scari2){
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
} else {
die('Woop, there seems to be a problem with the $scari2 variable. The value is:' . $scari2);
} // END OF INNER ELSE
} // END OF ELSE
And one more thing NEVER forget to use the mysql_real_escape_string() function on a variable before submiting it's value to the database.
I'm still learning more interesting details about PHP. Example: Moving from MySQL to MySQLi. What I am currently doing is trying enter something like this: http://music.daum.net/artist/main?artist_id=2289
From what I learned from pagination by dicing the url:
main?
artist_id=
2289
How can I be able to make a page like that? I have 2 sections available and will make the others when figuring this out.
artist information (available as testhub-artist.php)
album (available as testhub-artistalbum.php)
music video
photo section
I want to make it easier when making pages instead of making separate folders for each person.
My url would be: "../artist/detail?artist_id=#"
This is at the top of the artist page.
<?php
//Connect to ...
include "testhub-artist.php";
include "testhub-artistalbum.php";
?>
testhub-artist.php
<?php
//Connect to database
include "mysqli_connect.php";
// Construct our join query
$sql = "SELECT * FROM individuals WHERE soloID = 1";
// Create results
$result = mysqli_query($link, $sql);
// Checking if query is successful
if($result){
// Print out the contents of each row into a table
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
// If else states on each variable
if ($profilepic = $row['profilepic']){
$profilepic = $row['profilepic'];
}else{
$profilepic = "DamjuNoImage";
}
if ($engname = $row['engname']){
$engname = $row['engname'];
}else{
$engname = "Unknown";
}
if ($korname = $row['korname']){
$korname = $row['korname'];
}else{
$korname = "Unknown";
}
if ($engbn = $row['engbn']){
$engbn = $row['engbn'];
}else{
$engbn = "Unknown";
}
if ($korbn = $row['korbn']){
$korbn = $row['korbn'];
}else{
$korbn = "Unknown";
}
if ($dateofbirth = $row['dateofbirth']){
$dateofbirth = $row['dateofbirth'];
}else{
$dateofbirth = "Unknown";
}
if ($occupation = $row['occupation']){
$occupation = $row['occupation'];
}else{
$occupation = "Unknown";
}
if ($debut = $row['debut']){
$debut = $row['debut'];
}else{
$debut = "Unknown";
}
if ($recordlabel = $row['recordlabel']){
$recordlabel = $row['recordlabel'];
}else{
$recordlabel = "Unknown";
}
if ($officialsite = $row['officialsite']){
$officialsite = $row['officialsite'];
}else{
$officialsite = "#";
}
if ($sitename = $row['sitename']){
$sitename = $row['sitename'];
}else{
$sitename = "Unknown";
}
} // End of while statement
}else{
$engname = "Unknown";
$korname = "Unknown";
$engbn = "Unknown";
$korbn = "Unknown";
$dateofbirth = "Unknown";
$occupation = "Unknown";
$debut = "Unknown";
$recordlabel = "Unknown";
$officialsite = "#";
$sitename = "Unknown";
} // End of If statement
// Free result set
//mysqli_free_result($result);
?>
testhub-artistalbum.php
<?php
//connect to db
include "mysqli_connect.php";
//check for a page number. If not, set it to page 1
if (!(isset($_GET['albumpage']))){
$albumpage = 1;
}else{
$albumpage = $_GET['albumpage'];
}
//query for record count to setup pagination
$sqli = "SELECT * FROM albums WHERE soloID = 3";
$album_data = mysqli_query($link, $sqli);
$album_rows = mysqli_num_rows($album_data);
//number of photos per page
$album_pagerows = 4;
//get the last page number
$last_album = ceil($album_rows/$album_pagerows);
//make sure the page number isn't below one, or more than last page num
if ($albumpage < 1){
$albumpage = 1;
}elseif ($albumpage > $last_album){
$albumpage = $last_album;
}
//Set the range to display in query
$max_album = 'limit ' .($albumpage - 1) * $album_pagerows .',' .$album_pagerows;
//get all of the photos
$albumList = "";
$sqli2 = "SELECT * FROM albums WHERE soloID = 3 ORDER BY releasedate DESC $max_album";
$album_sql = mysqli_query($link, $sqli2);
//check for photos
$albumCount = mysqli_num_rows($album_sql);
if ($albumCount > 0){
while($album_rows = mysqli_fetch_array($album_sql)){
$albumID = $album_rows["albumID"];
$albumpic = $album_rows["albumpic"];
$title = $album_rows["albumTitle"];
$releasedate = $album_rows["releasedate"];
$page = $album_rows["page"];
$albumList .= '
<li class="albumthumb">
<img class="profile" src="../albums/album_th/' . $albumpic . '.jpg" alt="' . $albumpic . '" width="120" height="120" border="0" /><p class="datatitle">' . $title . '</p><p class="data-releasedate">' . $releasedate . '</p>
</li>
';
}
}else{
$albumList = "There are no available albums at this time!";
}
//mysql_close();
?>
Sorry for not explaining clearly. I want to be able to use pagination when making a profile page like the url. I want to use the number in the url to change the id (soloID) in the sql code.
Good idea in saving time, right? MySQLi getting easier every time I see it.
Thank you.
Changed 5/31/2012 5:44PM CT
$artist = $_GET['artist_id']
into
if(is_numeric($_GET['artist_id'])){
$artist = $_GET['artist_id'];
}else{
$artist = 1;
}
artist/detail?artist_id=#
You would use detail as the page, (probably have a detail folder with a index) and on the detail page, have a $_GET[] variable somewhere that gets the artist_id. So your code could look something like this:
$artist = $_GET['artist_id']; // Filter this variable
$sql = "SELECT * FROM individuals WHERE soloID = '{$artist}'";
/**
* Verify if the ID exists
* Display query results, etc.
*/
So everytime you change the artist_id variable in the URL, the page should change accordingly.
Welcome to my second favorite language! I love php.
Someone already answered your question, but I have some suggestions.
The code you have isn't vulnerable as is cause the user provided data is passed through math... but inlining variables is a good way to leave yourself open to SQL Injection attacks. Look up bind_param() and prepared statements and get in the habit of using them. Always. Well almost always..
Unfortunately SQL doesn't allow you to bind things like the values you use for LIMIT,ORDER BY,GROUP BY so you have to handle those yourself.
Never trust anything derived from a user, so do the work and check it.
Sort columns should always be column names. Check them.
if ( ! in_array($sort_column,array('column1','column2','column3') ) ) $sort_column = 'column1';
Limits should always be integers. Cast them as such.
$safe_limit = (int) $user_limit;
There is no need to copy the array values into another variable. Just use them directly.
You need to escape your values going into html. Lookup urlencode() and htmlentities().
My IE is up to a gig of memory so I'll have to finish this up later.