update multiple author in php but not same value - php

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.

Related

How to Delete a row of a table with using Psedo-Class in MySQL

I have created a database with a table and that table with one column of varchar datatype.
Now I want to delete the rows without using
DELETE FROM songs_list WHERE songs_name = 'Shakira Waka Waka'
This is so because I cannot write the name of the checkbox with spaces. For example:
<?php for ($printedsno=1; $printedsno <$noio+1 ; $printedsno++){?>
<?php while($row = mysqli_fetch_assoc($query7) ):?>
<input type="checkbox" name="<?php echo "cb".$row['songs_name'];?>"/>
<?php echo $printedsno?> <?php echo $row['songs_name']?></br>
<?php
break;
endwhile;
}
?>
Here We can not write the checkbox name as <?php echo "cb".$row['songs_name'];?>
That is why I want to use a psudo-Column. But For the Psudo-Column We can not be able to use a where clause beacause this column does'nt exist.
I want to delete the row from table with only column.
<?php
include 'database.php';
$noofsongs = "select * from songs_list";
$query8 = mysqli_query($con, $noofsongs);
$noio = mysqli_num_rows($query8);
$flag = 0;
$del = 0;
$row = mysqli_fetch_assoc($query8);
$song_names = $row['songs_name'];
if(isset($_POST['deletethis'])){
for($j=1; $j<=$noio ;$j++){
while($row = mysqli_fetch_assoc($query8) ){
if (isset($_POST['cb'.$song_names])){
$deletesongsquery = "DELETE FROM `songs_list` WHERE `songs_name` = $song_names" ;
$query4 = mysqli_query($con, $deletesongsquery);
if($query4){ $del++;}
$flag = $flag + 1;
}
}
}
if($del != $flag){echo "Can Not Be Deleted All Selected Songs.";}
else{echo "Deleted $del Selected Songs.";}
}
?>
Can anyone help me in this??

When my page loads it displays the previous mysql query result not the current one

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;
}

Have 4 'ands' in a select statement

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.

Select the right data in PHP

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.

PHP Validating Submit

I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query

Categories