I am working on an synonym/alias manager database where the user has the ability to store an association they feel is right. Say the user types in "rabbit" and no synonyms or aliases are found. The user then decides to associate "rabbit" with "bunny" and stores that into a database. Anytime any other user types in "bunny" the results for "rabbit" will appear. However, I am trying to implement a polling system asking the user if they feel the association is correct. If they think "bunny" fits "rabbit" then they vote yes, otherwise no. This is where I am stuck. As soon as I load the poll and press submit everything disappears and nothing gets sent to the database. Code is below:
$query = "SELECT * from searchtestdb where engname in ( SELECT synonyms.synonym FROM words LEFT JOIN synonyms ON synonyms.word_id = words.word_id WHERE word LIKE '%$searchBox%') "; // Query for animals in db
$query = mysql_query($query);
if(mysql_num_rows($query) == 0)
{
echo "<h2>Aliases: </h2>";
echo "Sorry, but we can not find an alias to match your query.";
echo "<br> ";
}
else
{
echo "<h2> Results using Alias: </h2>";
while($result = mysql_fetch_array($query))
{
$query2 = "SELECT * from searchtestdb where engname LIKE '%".$result['engname']."%';";
$result2 = mysql_query($query2);
while($row = mysql_fetch_array($result2))
{
print "<h4>Latin Name: </h4> ";
echo $row["latname"];
echo "<br> ";
print"<h4>English Name:</h4> ";
echo $row["engname"];
echo "<br>";
print "<h4> Species: </h4> ";
echo $row["spectype"];
print "<h4>Characteristics: </h4> ";
echo $row["charc1"];
echo "<br>";
echo $row["charc2"];
echo "<br>";
echo $row["charc3"];
echo "<br>";
}
}
$self = $_SERVER['PHP_SELF'];
print "<form method='post' action='$self' >\n";
print "<h4>Alias Association Correct? : </h4>";
print "<p>" .
"<input type='radio' name='vote' id='vote' value='1' /> \n" .
"Yes" .
"<input type='radio' name='vote' id='vote' value='2' /> \n" .
"No" .
"</p> \n" .
"<p>" .
"<input type='submit'name='submitVote' value='Submit' />" .
"\n </p> \n" .
"</form> \n" .
$vote=htmlentities($_POST['vote']);
echo $vote;
mysql_connect(----------------------) or die(mysql_error());
mysql_select_db("-----------") or die(mysql_error());
if($vote == 1)
{
mysql_query("INSERT INTO items(yes, uNo, word_id) VALUES ('0', '0', bunny');");
mysql_query("UPDATE items SET yes=yes+1 WHERE word_id='bunny';");
echo 'Thanks for voting Yes!';
}
if($vote == 2)
{ mysql_query("INSERT INTO items(word_id) VALUES ('".$result['engname']."'') ");
mysql_query("UPDATE items SET uNo=Uno+1 WHERE word_id='".$result['engname']."'");
echo "changos";
}
}
In a nutshell I made a small mistake:
$self = $_SERVER['PHP_SELF'];
should be
$self = $_SERVER['POST'];
Thanks Anyway.
Related
How do I delete one single row with the code that I have. It allows me to delete all rows instead of one single row with an ID not sure what im doing wrong not sure if its the loop I have or what.
<?php
include_once('dbconnect.php');
echo "<form action='delete.php' method='post' id = 'deleteForm'>";
$sqlARTICLEQuery = "SELECT * FROM articles where pageId=$paqueryRow[pageId] order by articleId";
$articlequeryResult = mysqli_query($conn,$sqlARTICLEQuery);
while ($articlequeryRow = mysqli_fetch_assoc($articlequeryResult))
{ echo "<input type = 'radio' name = '$articlequeryRow[articleId]' method = 'post'>".$articlequeryRow['articleId']." ".$articlequeryRow['articleTitle']." ";
echo "<input name='ARTSubmit' type='submit' value='delete record' /><br/>";
if (isset($_POST['ARTSubmit'])){
$artDeleteQuery = "DELETE FROM articles where pageId = $paqueryRow[pageId] AND articleId=$articlequeryRow[articleId].";
if(mysqli_query($conn, $artDeleteQuery)){
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error ($conn);
}
}
$sqlTEXTQuery = "SELECT * FROM text where articleId=$articlequeryRow[articleId] order by textId";
$textqueryResult = mysqli_query($conn,$sqlTEXTQuery);
while ($textqueryRow = mysqli_fetch_assoc($textqueryResult))
{
echo "<input type = 'radio' name = '$textqueryRow[textId]' method = 'post'>".$textqueryRow['textId']." ".$textqueryRow['textTitle']." "; //how can I print articles.pageId to match with pages.pageId
echo "<input name='TEXTSubmit' type='submit' value='delete record' /><br/>";
if (isset($_POST['TEXTSubmit'])){
$textDeleteQuery = "DELETE FROM text where articleId = $articlequeryRow[articleId] AND textId = $textqueryRow[textId].";
if(mysqli_query($conn, $textDeleteQuery)){
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error ($conn);
}
}echo "<br />"
}echo "<br />"
}echo "</form>"
$conn->close();
?>
You forgot a end quote on line 2 from the echo. and i removed the dot behind you query on line 20 your delete line. hope it helps.
include_once('dbconnect.php');
echo "<form action='delete.php' method='post' id = 'deleteForm'>";
$sqlARTICLEQuery = "SELECT * FROM articles where pageId=$paqueryRow[pageId] order by articleId";
$articlequeryResult = mysqli_query($conn,$sqlARTICLEQuery);
while ($articlequeryRow = mysqli_fetch_assoc($articlequeryResult))
{ echo "<input type = 'radio' name = '$articlequeryRow[articleId]' method = 'post'>".$articlequeryRow['articleId']." ".$articlequeryRow['articleTitle']." ";
echo "<input name='ARTSubmit' type='submit' value='delete record' /><br/>";
if (isset($_POST['ARTSubmit'])){
$artDeleteQuery = "DELETE FROM articles where pageId = $paqueryRow[pageId] AND articleId=$articlequeryRow[articleId].";
if(mysqli_query($conn, $artDeleteQuery)){
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error ($conn);
}
}
$sqlTEXTQuery = "SELECT * FROM text where articleId=$articlequeryRow[articleId] order by textId";
$textqueryResult = mysqli_query($conn,$sqlTEXTQuery);
while ($textqueryRow = mysqli_fetch_assoc($textqueryResult))
{
echo "<input type = 'radio' name = '$textqueryRow[textId]' method = 'post'>".$textqueryRow['textId']." ".$textqueryRow['textTitle']." "; //how can I print articles.pageId to match with pages.pageId
echo "<input name='TEXTSubmit' type='submit' value='delete record' /><br/>";
if (isset($_POST['TEXTSubmit'])){
$textDeleteQuery = "DELETE FROM text where articleId = $articlequeryRow[articleId] AND textId = $textqueryRow[textId].";
if(mysqli_query($conn, $textDeleteQuery)){
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error ($conn);
}
}echo "<br />"
}echo "<br />"
}echo "</form>"
$conn->close();
?>
In my database and more specific in the table named portfolio a user with a speficic username can store more than one data. The columns of the database are id,username,portfolio and portfolio_description
and I want to echo in my web page all the data for this username for example username=nbourlai. Until now I can echo only the first row for each username what is the loop that i can use in order to echo as many time is the id number.
Below is the current result and i want to create Portfolio and Portfolio description to be displayed with the appropriate values as many time as the highest id number is for the specific user.
Here is my code...
$portfolio = queryMysql("SELECT portfolio,portfolio_description FROM portfolio WHERE username='nbourlai'");
$row = mysql_fetch_row($portfolio);
echo "<h2>Portfolio</h2>";
echo "Portfolio: ";
echo stripslashes($row[0]) . "<br/>Portfolio Description: ";
echo stripslashes($row[1]) . "<br clear=left /><br />";
Can you help me please?
Are you looking for while loop like this?
$portfolio = queryMysql("SELECT portfolio,portfolio_description FROM portfolio WHERE username='nbourlai'");
echo "<h2>Portfolio</h2>";
while($row = mysql_fetch_row($portfolio)){
echo "Portfolio: ";
echo stripslashes($row[0]) . "<br/>Portfolio Description: ";
echo stripslashes($row[1]) . "<br clear=left /><br />";
}
or, like this?
$portfolio = queryMysql("SELECT username,portfolio,portfolio_description FROM portfolio ORDER BY username");
$username = '';
while($row = mysql_fetch_row($portfolio)){
if($username != $row[0]){
echo "<h1>".$row[0]."</h1>";
echo "<h2>Portfolio</h2>";
echo "Portfolio: ";
echo stripslashes($row[1]) . "<br/>Portfolio Description: ";
echo stripslashes($row[2]) . "<br clear=left /><br />";
}else{
echo "Portfolio: ";
echo stripslashes($row[1]) . "<br/>Portfolio Description: ";
echo stripslashes($row[2]) . "<br clear=left /><br />";
}
$username = $row[0];
}
I have followed several tutorials on here and I can't figure out my mistake.
The Gallery gets displayed correctly, and the check boxes have the right value when I check with Element inspector in Firefox, but this little script I wrote always unlinks the last picture in the loop, and the Database row does not get deleted.
Maybe you have a better eye for what I am missing then myself?
$sql = "SELECT id, title FROM houses ";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
echo $result['title'] . $result['id'];
echo"<br>";
$sql1 = "SELECT * FROM gallery_photos WHERE photo_category=" . $result['id'];
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_array($query1)) {
$photo_filename = $row['photo_filename'];
echo "<form action='' method='post'>
<li style='float:left; list-style-type:none;'>
<img src='houses/" . $photo_filename . "' title='$photo_filename' width='100px'>
<input type='checkbox' name='delete' value='$photo_filename'/> <br>
</li> ";
}
echo "<p style='clear:both' /> <input type='submit' value='Delete Selected' />";
echo" </form>";
echo "<p style='clear:both;'>";
echo "<br><br>";
}
if (isset($_POST['delete']) && is_array($_POST['delete']) && count($_POST['delete']) > 0) {
unlink("THIS/IS/A/WORKING/PATH/houses/" . $photo_filename);
unlink("THIS/IS/A/WORKING/PATH/houses/tb_" . $photo_filename);
mysql_query("DELETE FROM gallery_photos WHERE photo_filename = $photo_filename");
}
?>
You're opening the element each time for the new photo, but the submit button and only one closing tag are outside all of the forms. You may want to fix the html to have this working properly.
EDIT:
The wrong file gets deleted, because you're using $photo_filename variable in the last 3 rows instead of the value from $_POST['delete'].
Side note: this code is really awful and buggy. It's a security nightmare.
something like this should sort it, I have not tested it but hopefully it will work.
foreach ($_POST['delete'] as $filename) {
unlink("THIS/IS/A/WORKING/PATH/houses/" . $filename);
unlink("THIS/IS/A/WORKING/PATH/houses/tb_" . $filename);
mysql_query("DELETE FROM gallery_photos WHERE photo_filename = $filename");
}
echo '<form action='' method='post'>';
$sql = "SELECT id, title FROM houses ";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
echo $result['title'] . $result['id'];
echo"<br>";
$sql1 = "SELECT * FROM gallery_photos WHERE photo_category=" . $result['id'];
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_array($query1)) {
$photo_filename = $row['photo_filename'];
echo "<li style='float:left; list-style-type:none;'>
<img src='houses/" . $photo_filename . "' title='$photo_filename' width='100px'>
<input type='checkbox' name='delete[]' value='$photo_filename'/> <br>
</li> ";
}
echo "<p style='clear:both' /> <input type='submit' value='Delete Selected' />";
echo" </form>";
echo "<p style='clear:both;'>";
echo "<br><br>";
}
notice the [] at the end of the checkbox name, this means that it will create an array of them. You might want to add an additional check around the foreach to prevent it running if the $_POST['delete'] has not been set.
First, just to be sure, you are getting the params, you can use:
echo "<br />Contents of \$_POST:<br />";
foreach ($_POST as $k => $v) {
echo " $k = $v<br />";
}
So you know what params are you getting. And it looks like working.
Also, you can use it, to delete the images,
foreach ($_POST as $k => $v) :
if ( $k == "delete" ) :
// add your code for unlink and delete
endif;
endforeach;
Second, check for permissions before to delete
chmod($this->uploaddir . $this->finalName, octdec(0777)); // Maybe 0666 is enough
#unlink( path_to_file ); // # to avoid see code errors
And just, for you consideration, maybe if you use you don't have to be taking care about float, and clearing
Cheers
Hi I'm working on making a form to connect to a database. It works good so far. It displays information. However I want to include more then one field.
Like if I were only to enter "Oakland" in the "Location" form.
I think the isset field is the part I'm getting stuck at. I tried include '&!' or '||' to no effect. Or maybe its my html. I tried to include some code in the "isset" and it came up a "No data retrieved from server" error came up on browser. Because I only entered one field. I want to do it based on where the user enters information. BTW I do have a include in it to include the other files. Its just a snippet. It just I think that this is where my errors at.
Here is my html code. If you guys could help me figure out how to do this.
echo "<html>";
echo "<head>";
echo "<title>Your Title Here</title>";
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />";
echo "</head>";
echo "<body onLoad=\"self.focus();document.searchform.search.focus()\">";
echo "<center>";
echo "<br /><form name=\"searchform\" method=\"GET\" action=\"search.php\">";
echo "<input type=\"text\" name=\"search\" size=\"20\" TABINDEX=\"1\" />";
echo "<input type=\"text\" name=\"Institution\" size=\"20\" TABINDEX=\"1\" />";
echo "<input type=\"text\" name=\"Location\" size=\"20\" TABINDEX=\"1\" />";
echo "<input type=\"text\" name=\"ProjectNotes\" size=\"20\" TABINDEX=\"1\" />";
echo "<input type=\"text\" name=\"TotalFunding\" size=\"20\" TABINDEX=\"1\" />";
echo "<input type=\"text\" name=\"ActiveYear\" size=\"20\" TABINDEX=\"1\" />";
echo " <input type=\"submit\" value=\"Search\" />";
echo "</form>";
//search variable = data in search box or url
if (isset($_GET['search'])) {
$search = $_GET['search'];
Investigator($search);
}
Investigator function
function Investigator($search)
{
$search = trim($search);
$search = preg_replace('/\s+/', ' ', $search);
//seperate multiple keywords into array space delimited
$keywords = explode(" ", $search);
//Clean empty arrays so they don't get every row as result
$keywords = array_diff($keywords, array(
""
));
//Set the MySQL query
if ($search == NULL or $search == '%') {
} else {
for ($i = 0; $i < count($keywords); $i++) {
$query = "SELECT * FROM Studies " . "WHERE Investigator LIKE '%$keywords[$i]%'" . " OR Location LIKE '%$keywords[$i]%'" . " OR TotalFundingAmount LIKE '%$keywords[$i]%'" . " OR Institution LIKE '%$keywords[$i]%'" . " ORDER BY Location";
}
//Store the results in a variable or die if query fails
$result = mysql_query($query) or die(mysql_error());
}
if ($search == NULL or $search == '%') {
} else {
//Count the rows retrived
$count = mysql_num_rows($result);
echo $count;
}
//If search variable is null do nothing, else print it.
if ($search == NULL) {
} else {
echo "You searched for <b><FONT COLOR=\"blue\">";
foreach ($keywords as $value) {
print "$value ";
}
echo "</font></b>";
}
echo "<p> </p><br />";
echo "</center>";
//If users doesn't enter anything into search box tell them to.
if ($search == NULL) {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.</font></b><br /></center>";
} elseif ($search == '%') {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.</font></b><br /></center>";
//If no results are returned print it
} elseif ($count <= 0) {
echo "<center><b><FONT COLOR=\"red\">Your query returned no results from the database.</font></b><br /></center>";
//ELSE print the data in a table
} else {
//Table header
echo "<center>";
echo "</center>";
//Colors for alternation of row color on results table
$color1 = "#d5d5d5";
$color2 = "#e5e5e5";
//While there are rows, print it.
while ($row = mysql_fetch_array($result)) {
//Row color alternates for each row
$row_color = ($row_count % 2) ? $color1 : $color2;
//table background color = row_color variable
echo "<center><table bgcolor=" . $row_color . ">";
echo "<tr>";
echo "<td>" . $row['Investigator'] . "</td>";
echo "<td>" . $row['TotalFundingAmount'] . "</td>";
echo "<td>" . $row['Institution'] . "</td>";
echo "</tr>";
echo "</table></center>";
$row_count++;
//end while
}
//end if
}
echo "</body>";
echo "</html>";
if ($search == NULL or $search == '%') {
} else {
//clear memory
mysql_free_result($result);
}
}
?>
isset() only checks to see if a variable is defined. empty() may be what you want to use in this case, because it will specifically check to see if the form input is empty.
Using this you can then construct a query which will be executed--in fact, it might eliminate the need for a separate function. I haven't looked too much at the function code you posted. But it would go something like this:
Say you have input fields x, y, and z. You want to be able to run a query that returns all the information matching any of these fields that are filled out. The script, then, would run the same pattern of code for each input, with $datax being the data from the form.
if (empty($datax) == false) //If the data is NOT empty...
{
$stringx = "column = {$datax}"; //Assign a chunk of a mySQL query requesting matching info to a string.
}
else //If the data IS empty...
{
$stringx = "1"; //Create the same variable, but make it 1. You'll see why.
}
//Repeat the above for $datay and $stringy, $dataz and $stringz, etc. Next is another if to make sure the entire form isn't left blank.
if (empty($datax) == true && empty($datay) == true && empty($dataz) == true)
{
//Code to return an "Empty form!" error
}
else
{
$query = "SELECT * FROM table WHERE " . $stringx . " AND " . $stringy . " AND " . $stringz;
//Continue to run query
}
What this does is construct a query from the data results. If, for example, a user searches for USA, a blank field, and industrial, (with fields being location, weather, and type respectively--again, all just an example) the query looks like:
SELECT * FROM table WHERE location = 'USA' AND 1 AND type = 'industrial'
Any fields left blank result in an AND 1 statement inserted, not affecting the query. Hope that clears things up a little, let me know if I can make further edits to help.
i try to make checkboxes. When i click checkbox it makes isPremium = 1 if i click a checked checkbox it makes isPremium = 0
However: when i click a checked checkbox it does not work..
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
$dbResult = mysql_query("select * from profiles");
echo "<form action='#' method='post'>";
$dbResult = mysql_query("select * from profiles");
while ($info = mysql_fetch_array($dbResult)) {
if ($info['isPremium'] == 0)
echo "<input type=checkbox name='check2[]' id='check2' value=" . $info['id'] . ">";
else
echo "<input type=checkbox name='check1[]' id='check1' value=" . $info['id'] . " checked>";
echo $info['profileName'] . "<br />";
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
if (isset($_POST['btnPremium'])) {
if (isset($_POST['check2'])) {
$arrPremium = $_POST['check2'];
foreach ($arrPremium as $result) {
mysql_query("UPDATE profiles set isPremium=1 where id=" . $result . "");
}
}
else
{
$arrPremium = $_POST['check1'];
foreach ($arrPremium as $result2) {
mysql_query("UPDATE profiles set isPremium=0 where id=" . $result2 . "");
}
}
}
?>
when i click a checked checkbox it makes another checkbox unclick.
This is the checkbox page
I have refactored your code into this:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
$update = (isset($_POST['check']) && is_array($_POST['check']));
$dbResult = mysql_query("select * from profiles");
echo "<form action='#' method='post'>";
while ($info = mysql_fetch_array($dbResult))
{
if ($update)
{
$info['isPremium'] = (in_array($info['id'], $_POST['check']) ? 1 : 0);
mysql_query("UPDATE profiles SET isPremium = " . $info['isPremium'] . " WHERE id = " . $info['id']);
}
echo "<input type=checkbox name='check[]' value=" . $info['id'] . ($info['isPremium'] == 0 ? "" : "checked") . " />";
echo htmlspecialchars($info['profileName']) . "<br />";
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
?>
There were several problems with your original code:
Several HTML input elements with the same ID. This is wrong. We can have several elements with the same name attribute, but the id attribute should be unique for each element.
The database UPDATE code runs after displaying the form. This is wrong. In this case, we should update the database prior to generating the HTML output.
IMPORTANT: There is no need of two different POST arrays (check1 and check2). We only need one array. The checked boxes will be posted by the browser. The unchecked boxes will not be posted by the browser. As the id is the value, we can use the in_array function to verify if the checkbox for an item was checked or not.
It is a good idea to escape things you will output as HTML from the database. Otherwise, the application is vulnerable for some kinds of attack. The function htmlspecialchars is useful for this purpose.
If I understand correctly what you're trying to achieve, your code is needlessly complicated. You should use isset to check whether the value of a checkbox was included in the $_POST array. If yes, the checkbox was checked.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
echo "<form action='#' method='post'>";
$dbResult = mysql_query("SELECT * FROM profiles");
$profileid = array();
while ($info = mysql_fetch_array($dbResult)) {
echo "<input type=\"checkbox\" name=\"" . $info['id'] . "\" " . ($info['isPremium'] != 0 ? "checked " : "") . "/>";
echo $info['profileName'] . "<br />";
$profileid[] = $info['id'];
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
if (isset($_POST['btnPremium'])) {
foreach ($profileid as $id) {
if (isset($_POST[$id])) {
mysql_query("UPDATE profiles SET isPremium=1 WHERE id=" . $id);
} else {
mysql_query("UPDATE profiles SET isPremium=0 WHERE id=" . $id);
}
}
}
?>
Checkboxes typically send the value "on" to the server, regardless of what value attribute is set. If you can, try to use radio buttons instead, as these send the proper value to the server. If that's not an option, have the name of the checkbox be check1[".$info['id']." and access array_keys($_POST['check1']).