Issue with php/mysql inserting entry with checkbox checked into database - php

Below is the code from catalog page with the data which has to be inserted to the database. It has some problem and i cant insert that data to the database table, and i think i have not ported variables correctly.
My catalogue page has this code (it is for purchasing photographs):
while ($row=mysql_fetch_assoc($result))
{
echo "<tr><td width=100><img src=".$row['FilePath']." /></td>";
echo "<td width=100 padding=25>".$row['Title']."</td>"; $hour = time() + 3600; setcookie('titlecookie', $row['Title'], $hour);
echo "<td width=100 padding=25>".$row['Cost']."</td>";
echo "<td width=100>".$row['FileSize']."</td>";
echo "<td width=100>".$row['CaptureDate']."</td>";
echo "<td width=100>".$row['Resolution']."</td>";
echo "<td width=100><input type=checkbox name=checked[] value=select />Purchase</td></tr>";
}
echo "</table><input type=submit name=submit value=Purchase></form></center>";
}
else
{
echo "Query not successful";
}
The code for my purchase page appears as follows:
$username = "COOKIE['ID_my_site']";
$title = "COOKIE['titlecookie']";
$Custid = mysql_query("SELECT Custid from Customer Where Username=$username");
$Money = $_POST['Cost'];
$Photoid = mysql_query("SELECT Photoid from Photograph Where Title = $row[Title]");
foreach ($_POST['checked'] as $select) {
if(mysql_query('INSERT INTO Transaction (Money, Custid)
VALUES ($Money, $Custid)'))
{
echo "successfully added to Transaction";
}
else
{
echo "Problems adding data to Transaction";
}
if(mysql_query("INSERT INTO TransPhoto (Photoid, Transid)
VALUES ('$Photoid', '$Transid')"))
{
echo "successfully added to Transphoto";
}
else
{
echo "Problems adding data to Transphoto";
}
}
Could you possible assist me with fixing this code? I am relatively new to this but have searched and could not find an effective solution. Thanks

Related

while loop always print last inserted row result

Problem is while loop always showing last inserted row result. I've tried this below code to follow/unfollow button option. For example I'm a user id=1. I have already followed user id=4. Now, I want to follow user id=5. When i click follow button(id=5) it turns into Unfollow properly. But, I have already followed user id=4. That turns into Follow. This is my problem.
Then I tried echo $following;. it Prints 5555. That means last inserted data. But I want 45. I'm sure I've made a mistake in my while loop. But I don't know what I should change?
<?php
try
{
$stmt = $conn->prepare("SELECT * FROM users ORDER BY Autoid");
$stmt->errorInfo();
$stmt->execute();
$sth = $conn->prepare("SELECT * FROM followers ORDER BY Autoid");
$sth->errorInfo();
$sth->execute();
while($follow_row = $sth->fetch(PDO::FETCH_ASSOC))
{
$following = $follow_row['Following'];
$follower = $follow_row['Follower'];
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td>". $row['Autoid'] ."</td>";
echo "<td>". $row['Name'] ."</td>";
// echo $row['Following'];
if($_SESSION['sesuname'] == $row['Username'])
{
echo "<td class='itsyou' >Its You ". $_SESSION['sesuname'] ."</td>";
}
else
{
if(($follower == $_SESSION['sesid']) AND ($following != $row['Autoid']))
{
//echo "<td>true</td>";
echo $following;
echo "<td>";
echo "<form id='jsform' method='post' action='subscribe.php'>";
echo "<input type='hidden' name='id' value=" . $row['Autoid'] . " />";
echo "<button class='follow' >Follow</button>";
echo "</form>";
echo "</td>";
}
else
{
//echo "<td>false</td>";
echo "<td>";
echo "<form id='ufform' method='post' action='unsubscribe.php'>";
echo "<input type='hidden' name='uid' value=" . $row['Autoid'] . " />";
echo "<button class='follow' >UnFollow</button>";
echo "</form>";
echo "</td>";
}
}
echo "</tr>";
}
} catch (PDOException $e) {
'Database Error : ' .$e->getMessage();
}
?>
This code:
while($follow_row = $sth->fetch(PDO::FETCH_ASSOC))
{
$following = $follow_row['Following'];
$follower = $follow_row['Follower'];
}
Simply OVERWRITES $following and $follower every time you fetch a row, leaving you with the LAST row fetched in the variables. Perhaps you want something more like
$following[] = $follow_row['Following'];
$follower[] = $follow_row['Follower'];
^^--- append new row value to an array.

Send individual array results to printer based on id table

I'm working on a simple PHP script that stores user details in a MySQL database. I can run a query and have it return the individual records as long as the query matches the last name (pre-defined). Once I have the records, I want to be able to echo a print button next to each record so that the user can individually print each record.
The code is a mashup of several snippets of code and is working great, except the "print user data" part. I'm not a newbie in PHP, but I also know enough to navigate around a script. Here's what I've got so far.
<?php
//capture search term and remove spaces at its both ends if the is any
$searchTerm = trim($_GET['keyname']);
//check whether the name parsed is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
//database connection info
$host = "localhost"; //server
$db = "users"; //database name
$user = "root"; //dabases user name
$pwd = "password1"; //password
//connecting to server and creating link to database
$link = mysqli_connect($host, $user, $pwd, $db);
//MYSQL search statement
$query = "SELECT * FROM details WHERE lastname LIKE '%$searchTerm%'";
$results = mysqli_query($link, $query);
/* check whether there were matching records in the table
by counting the number of results returned */
if(mysqli_num_rows($results) >= 1)
{
$output = "";
while($row = mysqli_fetch_array($results))
{
echo "<tr valign=bottom>";
echo "<td bgcolor=#ffffff background='img/dots.gif' colspan=6><img src=img/blank.gif width=1 height=1></td>";
echo "</tr>";
echo "<tr valign=center>";
echo "<td class=tabval><img src=img/blank.gif width=10 height=20></td>";
echo "<td class=tabval><b>".htmlspecialchars($row['firstname'])."</b> </td>";
echo "<td class=tabval>".htmlspecialchars($row['lastname'])." </td>";
echo "<td class=tabval>".htmlspecialchars($row['address'])."</td> ";
echo "<td class=tabval>".htmlspecialchars($row['phone'])." </td>";
echo "<button type=\"button\" class=\"formbutton\" onclick=\"printpage('" . $lastname . "'); \">Print User Data</button>";
echo "<td class=tabval></td>";
echo "</tr>";
$i++;
}
echo "<tr valign=bottom>";
echo "<td bgcolor=#fb7922 colspan=6><img src=img/blank.gif width=1 height=8></td>";
echo "</tr>";
echo $output;
}
else
echo "There was no matching record for the name " . $searchTerm;
?>
<br />
Done
echo "<button type=\"button\" class=\"formbutton\" onclick=\"printpage('" . $lastname . "'); \">Print User Data</button>";
This line is calling a javascript function called "printpage". Once you have that javascript function on the page, you'll be closer to your expected result.

how to get the value of generated password from the for loop

i manage my codes to generate a random password of my students(about 45 students) from my records table("tbl_studentreg"). now i want to save it to a new table(tbl_student) with the generated random password, but my problem is i couldnt get the data from the generated password.. pls help me and give me some advice.
<?php
function genpass(){
$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()_+';
return substr(str_shuffle($charset), 0, 12);
}
?>
<?php
if(isset($_POST['generate'])){
$generated_pass = $_POST['generate'];
genpass();
}
?>
<form method="post" action='enroll_student.php' name ='register'>
<?php
$yr = date("Y");
if ($result = $mysqli->query("SELECT
tbl_studentreg.studId,
tbl_studentreg.fname,
tbl_studentreg.lname,
tbl_studentreg.mname,
tbl_studentreg.dob,
tbl_studentreg.address,
tbl_department.departmentName,
tbl_studentreg.sy
FROM tbl_studentreg
Inner Join tbl_department ON tbl_studentreg.departmentId = tbl_department.departmentId WHERE tbl_studentreg.sy = '$yr' "))
{
if ($result->num_rows > 0)
{
echo "<table width= '1000'>";
echo "<tr><th>StudentID</th><th>Name</th><th>Date of Birth</th><th>Address</th><th>Department</th><th>School Year</th><th>Password</th></tr>";
while ($row = $result->fetch_object())
{
echo "<tr>";
echo "<td align='center'>" . $row->studId . "</td>";
echo "<td align='center'>" . $row->fname . " ". $row->mname ." ". $row->lname ." </td>";
echo "<td align='center'>".$row->dob."</td>";
echo "<td align='center'>" . $row->address. "</td>";
echo "<td align='center'>".$row->departmentName."</td>";
echo "<td align='center'>".$row->sy."</td>";
if(isset($generated_pass)) {
for($i=0; $i <= $row->studId; $i++){
$generated_pass = genpass($i);
echo "<td>$generated_pass</td>";
}
}
if(isset($_POST['save'])) {
//here i want to pass the value of my generated pass,
//i use global $generated_pass but still dont work.
$save = $_POST['save'];
$insert = $mysqli->query("INSERT INTO tbl_student
(studId, fname, lname, mname, password, dob, address,
f_fname, f_mname, f_lname, m_fname, m_mname, m_lname, departmentId)
VALUES ('".$row->studId."', '".$row->fname."', '".$row->lname."',
'".$row->mname."', '$generated_pass', '".$row->dob."', '".$row->address."',
'".$row->f_fname."', '".$row->f_mname."', '".$row->f_lname."',
'".$row->m_fname."', '".$row->m_mname."', '".$row->m_lname."',
'".$row->departmentId."')");
}
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No Results.";
}
}
else
{
echo "Error: " . $mysqli->error;
}
$mysqli->close();
echo '<br>';
include 'count.php'; //this one will give the total no. of results, just ignore.
?>
<br />
<tr><td></td></tr><tr><td><input type='submit' name='generate' value='Generate'/></td></tr>
</table>
</form>
<form action="enroll_student.php" method="post" name="save">
<input type='submit' name='save' value='Save'/>
</form>
Since you figured out the posting problem, add password security:
function genpass($userEmail){
$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()_+';
$pss= substr(str_shuffle($charset), 0, 12);
YourFunctionSendEmailWithPassword(userEmail, $pss); //email password to user
$salt = sha1(md5(pss));
$password = md5(pss . $salt);
return $password;
}
This will add some security to your passwords

Deleting one row from the database using the ID

I have problems with deleting a record from the screen using MSQLI.
Here you can see the code i'm using.
<?php
include_once("assets/classes/connection.php");
include_once("assets/classes/article.class.php");
while($test = $allArticles->fetch_assoc())
{
if($test['titel']=="")
{
echo "<div class='zonderfoto'>";
echo "<h5>"."geen titel hier, aparte opmaak geslaagd" . "<br /></h1>";
echo "<p>" . $test['article'] . "</p>";
echo "<input type='submit' name='verwijderee' value='verwijder'>";
echo "</div>";
}
else
{
echo "<div class='metfoto'>";
echo "<h1>".$test['titel'] . "<br /></h1>";
echo "<p>" . $test['article'] . "</p>";
echo "<form method='post' action=''>";
echo "<input type='submit' name='verwijder' value='verwijder'>";
echo "</form>";
echo "<h1>".$test['id']."</h1>";
echo "</div>";
}
}
$vArticle = new Article;
$vArticle -> Key = $test['id'];
if (isset($_POST['verwijder']))
{
$vArticle -> deleteArticle();
echo ("shit");
}
?>
I'm using a while function to print all the DB records on the screen. The if function is just a function to give some design with css so nothing more. With the delete button i want to delete the record from the screen. With the $test['id'] variabele you receive the ID of the record in the DB
Ok here is my code from the class.
public function deleteArticle()
{
include("connection.php");
$sSql = "DELETE FROM tblArticles WHERE id = '".$this->m_sKey."'";
if (!$mysqli -> query($sSql))
{
throw new Exception("Something went wrong");
}
}
EDIT
There is something wrong with the key, i replaced the where statement with title ="", so i deleted one title in the database, and when i click on delete then, he delete one row, but this is not happening at runtime. so i click delete, one row deleted, BUT the content only dissapear with a page refresh. The solution is using ajax?
public function deleteArticle()
{
include("connection.php");
$sSql = "DELETE FROM tblArticles WHERE id = '".$this->m_sKey."'";
$mysqli->query($sSql);
$aff_rows = $mysqli->affected_rows;
if ($aff_rows){
print("Affected rows (DELETE): %d\n", $aff_rows);
}
else{
print("Nothong Happend ?");
if ($err = $mysqli->error){
print("Error: %s\n", $err);
}
}
}

PHP Insert Multidimensional Array into mysql

i try to store the booking booths into database based on user selection, there are 10 check boxes for each booths and user can choose which day they want to reserve booths. For each check box has it own field in database, if user choose booth A01, D1 and D2, when he press reserve button, it will insert value into D1 and D2. But I dont know how to get the checked checkbox value to store in database
my booth interface
http://i.imgur.com/umYcI.gif
my table structure
http://i.imgur.com/vKh6R.gif
My coding
<?php
session_start();
if ( !isset($_SESSION['AUTHORIZED_USERNAME']) || empty($_SESSION['AUTHORIZED_USERNAME']) ) {
header("location:index.php");
}else{
$user=$_SESSION['AUTHORIZED_USERNAME'];
}
include('db.php');
if($_REQUEST){
$id = $_REQUEST['search_category_id'];
$query2 = mysql_query("SELECT filenameBig, filename, url FROM eventinfo where eventID ='$id'");
$row = mysql_fetch_array($query2, MYSQL_ASSOC);
if($id == -1)
{
echo "<style type='text/css'>#btn_submit{visibility:hidden}</style>";
}
else{
/*echo "<a href='{$row['url']}'>Click me!</a>";*/
echo "<p><br><img src='{$row['filename']}' alt='' /></p>";
echo "<p></p>";
echo "<p align='right'><a href='$row[filenameBig]' target='_blank'>Click to view large image</a></p>";
echo "<hr size='1'>";
echo "<div style='padding-left:4px;' align='left'><strong>Booths Listing</strong>";
echo "<p></p>";
$query = "select boothAlias, totalDay from booths, eventinfo where booths.eventID=eventinfo.eventID && booths.eventID = ".$id."";
$_SESSION['EVENT_ID']=$id;
$result = mysql_query($query);
$result2= mysql_query($query);
echo "<table border='0' style='width:400px;table-layout:fixed' >";
$rows2 = mysql_fetch_array($result);
$Day=$rows2['totalDay'];
echo "<table>";
for ($day = 0; $day <= $Day; ++$day) {
if($day==0){
echo "<th>Booth</th>";
}else{
echo "<th>D".$day."</th>";
}
}
while($rows = mysql_fetch_array($result2)){
$boothAlias=$rows['boothAlias'];
$totalDay=$rows['totalDay'];
echo "<tr><td>$boothAlias</td>";
for ($day2 = 1; $day2 <= $totalDay; ++$day2) {
echo "<td><input name='day2[]' type='checkbox' value='$day2' /></td>";
}
echo "</tr>";
}
echo "</table>";
}
}
?>
I think that SET type would be good solution for this.
http://dev.mysql.com/doc/refman/5.0/en/set.html

Categories