PHP/MySQL multiple values in same column - php

I'm trying to build a page where my users can paste in multiple item #s for that product and it will give them the parent model # for that particular item, where items are given individual identifiers.
However, my users paste there information into the textboxs, but it doesn't pull anything up. When I had one value to search it was able to find the items. My table structure is very simple.Fcsku varchar(45), fnsku varchar(45), updated time(45 are not important to this function).
Here is my query Updated:
<form action="" method="get">
Paste your ZZZ's here: <br><input type="text" name="item" id="textbox"/><br>
<input type="text" name="item2" id="textbox2"/>
<script>document.getElementById('textbox').focus()</script><br />
<input type="submit" value="Submit"/>
</form>
<?php
if (!empty($_REQUEST['item'])) {
$item = mysql_real_escape_string($_REQUEST['item']);
$item2 = mysql_real_escape_string($_REQUEST['item2']);
$sql = "select * from oak3_zzz_to_boo WHERE fcsku like '%".$item."%' or fcsku like '%".$item2."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)) {
echo "<font color=red size=7>";
echo '<center><br /> Parent ASIN: '.$row['fnsku'];
echo "</center></font>";
echo "<br><br><br><br><br>";
}
}
?>

This worked at my server:
<form action="" method="post">
Paste your ZZZ's here:<br />
<input type="text" name="item" id="textbox" /><br />
<input type="text" name="item2" id="textbox2"/><br />
<input type="submit" value="Submit" name="submit"/>
<script>document.getElementById('textbox').focus()</script>
</form>
<?php
if (isset($_POST['submit'])) {
$item = mysql_real_escape_string('%'.$_POST['item'].'%');
$item2 = mysql_real_escape_string('%'.$_POST['item2'].'%');
$sql = "SELECT * FROM oak3_zzz_to_boo WHERE fcsku LIKE '" . $item . "' OR fcsku LIKE '" . $item2 . "'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_assoc($r_query)) {
echo "<font color=red size=7>";
echo '<center><br />Parent ASIN: ' . $row['fnsku'];
echo "</center></font>";
echo "<br /><br /><br /><br /><br />";
}
}
?>

Related

Something wrong while deleting data from DB

I'm trying to delete some information from the database, but when I ask the user to confirm action, something goes wrong. Can you help me?
The script prints the categories to choose if nothing is settled. Then, It asks the user to delete or not delete the categories chosen. In the end, it deletes what was chosen.
But there's some error in the last part(first in the script) and I cannot understad where it's going wrong:
<?php
//If the user confirm to delete...
if(isset($_POST['eliminazione_conferma']) and $_POST['eliminazione_conferma']=='conferma'){
//if conferma_eliminazione=1, don't delete
if(isset($_POST['conferma_eliminazione']) and $_POST['conferma_eliminazione']=='1'){
echo 'Eliminazione annullata';
}else{//Delete if conferma_eliminazione=0
while($row=$categoria){
$delete= "DELETE FROM categorie WHERE $row = category_id";
$query=mysql_query($delete);
echo "$row eliminato\n";
}
}
}else{//ELSE, print the form to confirm action
if(isset($_POST['eliminazione']) and $_POST['eliminazione']=='delete'){
//Array with the chosen "categories"
$categoria=isset($_POST['categoria']) ? $_POST['categoria'] : array();
//Print the chosen categories to ask confirmation
echo'Sicuro di voler eliminare le seguenti categoire?<br />';
foreach($categoria as $row){
echo "$row<br />\n";
}
//Yes = 0, No = 1
echo '<form method="post" action="',$_SERVER['REQUEST_URI'],'">
<input type="radio" name="conferma_elimiazione" value="0" />Si<br />
<input type="radio" name="conferma_eliminzione" value="1" />No<br />
<input type="hidden" name="eliminazione_conferma" value="conferma" />';
foreach($categoria as $row){
echo'<input type="hidden" name="categoria[]" value="',$row,'" />',"\n",'' ;
}
echo'
<input type="submit" value="Conferma" />
</form>';
}else{//In the end, if nothing is settled, print the form to check the category to delete
//Select the categories from the database
echo'<form method="post" action="',$_SERVER['REQUEST_URI'],'" />',"\n",'';
$select = "SELECT nome,category_id FROM categorie ORDER BY category_id" ;
$select_result=mysql_query($select) or die("Mysql Error: ".mysql_error());
while($row = mysql_fetch_assoc($select_result)){
echo '<input type="checkbox" name="categoria[]" value="',$row['category_id'],'">',$row['nome'],'<br />';
}
echo'<input type="hidden" name="eliminazione" value="delete" />
<input type="submit" name="submit" value="Elimina" />
</form>';
}
}
The problem with the query
$delete= "DELETE FROM categorie WHERE $row = category_id";
is
here
WHERE $row = category_id";
What is category_id?
Do you have a value for that?
Probably you want WHERE category_id=/*something here like $row['column_name']*/
Thanks everyone for the help, but I've solved my problem in this way(the script wasn't transformig the value of "conferma_eliminazione" in the integer type):
<h2>Modifica o Elimina Categoria </h2>
<?php
if(isset($_POST['eliminazione_conferma']) and $_POST['eliminazione_conferma']=='conferma'){
$categoria=isset($_POST['categoria']) ? $_POST['categoria'] : array();
$a=(int)$_POST['eliminazione'];
if($a=='1'){
echo 'Eliminazione annullata';
echo "\n";
}elseif($a=='0'){
foreach($categoria as $row){
$delete= "DELETE FROM categorie WHERE $row = category_id";
$query=mysql_query($delete);
echo "$row eliminato\n";
}
}
}else{
if(isset($_POST['eliminazione']) and $_POST['eliminazione']=='delete'){
$categoria=isset($_POST['categoria']) ? $_POST['categoria'] : array();
echo'Sicuro di voler eliminare le seguenti categoire?<br />';
foreach($categoria as $row){
echo '',$row,'<br />',"\n";
}
echo '<form method="post" name="form_eliminazione_categoria" action="',$_SERVER['REQUEST_URI'],'">',"\n",'
<input type="radio" name="eliminazione" value="0" />Si<br />' ,"\n",'
<input type="radio" name="eliminazione" value="1" />No<br />',"\n",'
<input type="hidden" name="eliminazione_conferma" value="conferma" />',"\n",'';
foreach($categoria as $row){
echo '<input type="hidden" name="categoria[]" value="',$row,'" /><br />',"\n",'';
}
echo'
<input type="submit" value="Conferma" />
</form>';
}else{
echo'<form method="post" action="',$_SERVER['REQUEST_URI'],'" />',"\n",'';
$select = "SELECT nome,category_id FROM categorie ORDER BY category_id" ;
$select_result=mysql_query($select) or die("Mysql Error: ".mysql_error());
while($row = mysql_fetch_assoc($select_result)){
echo '<input type="checkbox" name="categoria[]" value="',$row['category_id'],'">',$row['nome'],'<br />';
echo "\n";
}
echo'<input type="hidden" name="eliminazione" value="delete" />',"\n",'
<input type="submit" name="submit" value="Elimina" />',"\n",'
</form>';
}
}

PHP/MySQL throwing me index error but it's already listed

PHP it's throwing at me
Notice: Undefined index: username in D:\xampp\htdocs\0100348514\pages\account.php on line 16
Warning: mysql_query() expects parameter 1 to be string, resource given in D:\xampp\htdocs\pages\account.php on line 19
But in my database I have it exactly the same 'username' but it's still throwing it at me any ideas?
Code on that page
<?php
$page = "My Account";
session_start();
include '../includes/config.php';
?>
<div id="searchbar">
<form action="search.php" method="get">
<input type="text" name="search" />
<input type="submit" name="submit" class="btn btn-primary" value="Search" />
</form>
</div>
</div>
<?php
$username = $_SESSION['username'];
$sql = "SELECT * FROM login WHERE username = '$username'";
$result = mysql_query($con, $sql) or die(mysql_error($con)); //run the query
$row = mysql_fetch_array($result);
?>
<div id="wrapper">
<section id="content" class="shadow">
<div id="titlebar">
<?php
echo $page = '<h1> My ACCOUNT </h1>';
?>
</div>
<br />
<?php
//user messages
if(isset($_SESSION['error'])) //if session error is set
{
echo '<div class="error">';
echo '<p class="center">' . $_SESSION['error'] . '</p>'; //display error message
echo '</div><br />';
unset($_SESSION['error']); //unset session error
}
elseif(isset($_SESSION['success'])) //if session success is set
{
echo '<div class="success">';
echo '<p class="center">' . $_SESSION['success'] . '</p>'; //display success message
echo '</div><br />';
unset($_SESSION['success']); //unset session success
}
?>
<div id='left'>
<form id="registration" form action="accountprocessing.php" method="post">
<br />
<fieldset><h1>Update Your Details</h1><br />
<ol>
<li>
<label>Username*</label> <input type="text" name="username" required value="<?php echo $row['username'] ?>" readonly />
</li>
<?php
//generate drop-down list for state using enum data type and values from database
$tableName='member';
$colState='state';
function getEnumState($tableName, $colState)
{
global $con; //enable database connection in the function
$sql = "SHOW COLUMNS FROM $tableName WHERE field='$colState'";
//retrieve enum column
$result = mysql_query($con, $sql) or die(mysql_error($con));
//run the query
$row = mysql_fetch_array($result); //store the results in a variable named $row
$type = preg_replace('/(^enum\()/i', '', $row['Type']); //regular expression to replace the enum syntax with blank space
$enumValues = substr($type, 0, -1); //return the enum string
$enumExplode = explode(',', $enumValues); //split the enum string into individual values
return $enumExplode; //return all the enum individual values
}
$enumValues = getEnumState('member', 'state');
echo '<select name="state">';
if((is_null($row['state'])) || (empty($row['state']))) //if the state field is NULL or empty
{
echo "<option value=''>Please select</option>"; //display the 'Please select' message
}
else
{
echo "<option value=" . $row['state'] . ">" . $row['state'] .
"</option>"; //display the selected enum value
}
foreach($enumValues as $value)
{
echo '<option value="' . $removeQuotes = str_replace("'", "",
$value) . '">' . $removeQuotes = str_replace("'", "", $value) . '</option>'; //remove the quotes from the enum values
}
echo '</select><br />';
?>
</li>
<p> </p>
<li>
<label>Postcode*</label> <input type="text" name="postcode" required value="<?php echo $row['postcode'] ?>"/>
</li><br />
<li>
<label>Country*</label> <input type="text" name="country" required value="<?php echo $row['country'] ?>"/>
</li><br />
<li>
<label>Phone</label> <input type="text" name="phone" value="<?php echo $row['phone'] ?>"/>
</li><br />
<li>
<label>Mobile</label> <input type="text" name="mobile" value="<?php echo $row['mobile'] ?>" />
</li><br />
<li>
<label>Email*</label> <input type="email" name="email" required value="<?php echo $row['email'] ?>" />
</li><br />
<li><label>Gender*</label>
<?php
//generate drop-down list for gender using enum data type and values from database
$tableName='member';
$colGender='gender';
function getEnumGender($tableName, $colGender)
{
global $con; //enable database connection in the function
$sql = "SHOW COLUMNS FROM $tableName WHERE field='$colGender'";
//retrieve enum column
$result = mysql_query($con, $sql) or die(mysql_error($con));
//run the query
$row = mysql_fetch_array($result); //store the results in a variable named $row
$type = preg_replace('/(^enum\()/i', '', $row['Type']); //regular expression to replace the enum syntax with blank space
$enumValues = substr($type, 0, -1); //return the enum string
$enumExplode = explode(',', $enumValues); //split the enum string into individual values
return $enumExplode; //return all the enum individual values
}
$enumValues = getEnumGender('member', 'gender');
echo '<select name="gender">';
echo "<option value=" . $row['gender'] . ">" . $row['gender'] .
"</option>"; //display the selected enum value
foreach($enumValues as $value)
{
echo '<option value="' . $removeQuotes = str_replace("'", "",
$value) . '">' . $removeQuotes = str_replace("'", "", $value) . '</option>';
}
echo '</select>';
?>
</li>
</ol>
</fieldset>
<br />
<fieldset>
<p>Subscribe to weekly email newsletter?</p><br />
<label>Yes</label><input type="radio" name="newsletter" value="Y" <?php if($row['newsletter'] == "Y"){echo "checked";} ?>><br />
<label>No</label><input type="radio" name="newsletter" value="N" <?php if($row['newsletter'] == "N"){echo "checked";} ?>>
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
</fieldset><br />
<p class="center"><input type="submit" name="accountupdate" value="Update Account" /></p><br />
</form>
</div>
<br />
<div id='right'>
<form id="registration" form action="accountimageprocessing.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
<br />
<fieldset><h1>Update Image</h1><br />
<?php
if((is_null($row['image'])) || (empty($row['image']))) //if the photo field is NULL or empty
{
echo "<p class='center'><img src='../images/members/member.png' width=150 height=150 alt='default photo' /></p>"; //display the default photo
}
else
{
echo "<p class='center'><img src='../images/members/" . ($row['image']) . "'" . 'width=150 height=150 alt="contact photo"' . "/></p><br />"; //display the contact photo
}
?>
<label>New Image</label> <input type="file" name="image" />
<br />
<p>Accepted files are JPG, GIF or PNG. Maximum size is 500kb.</p>
<br />
<p class='center'><input type="submit" name="imageupdate" value="Update Image" /></p>
</form>
<br />
<br />
<form action="accountpasswordprocessing.php" method="post">
<h1>Update Password</h1>
<br />
<p>Passwords must have a minimum of 8 characters.</p> <br />
<label>New Password*</label> <input type="password" name="password" pattern=".{8,}" title= "Password must be 8 characters or more" required />
<br />
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
<br />
<p class='center'><input type="submit" name="passwordupdate" value="Update Password" /></p>
<br />
</form>
<h1>Delete My Account</h1>
<br />
<p>We're sorry to hear you'd like to delete your account. By clicking the button below you will permanently delete your account.</p>
<br />
<form action="accountdelete.php" method="post">
<p class='center'><input type="submit" value="Delete My Account" onclick="return confirm('Are you sure you wish to permanently delete your account?');" ></p>
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>"><br />
</fieldset>
</form>
</div>
</section> <!-- end #content -->
<div id="footernav" class id="shadow">
<?php
require "../inc/footer.php";
?>
</div>
</div>
Your mysql_query parameteres are reversed. It should be:
mysql_query($sql, $con);
Also as you can see in the linked PHP Manual page, this extension is deprecated and alternatives should be used:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_query()
PDO::query()

If content exists in database, provide form to update it - else provide form to add new row

It's all going wrong. I need to output a form onto my website that will do 1 of 2 things:
If the user already has content in the database, provide a form that posts to self to update the existing content.
If the user does not have content in the database, provide a form to let the user add information to the database.
The forms should submit to themselves to keep coding tidy. I'm getting into a right mess. I'll show what I have so far, but I'm getting in a muddle.
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
while($row = mysql_fetch_array($result))
{
$profileText = $row['text'];
}
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
echo
'<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">' .
$profileText .'
</textarea><br />
<input type="submit" value="Submit" />
</form>'
;}
else{
$profileText = $row['text'];
echo
"<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>" .
$profileText
."</textarea><br />
<input type='submit' value='Submit' />
</form>"
;}?>
You've pretty much got the functionality there, just needs tidying up.
Try something like this:
<?php
//look in db to see if content exists, if it does set variable
$profileText="";
if($result = mysql_query("SELECT * from tbl_profiles WHERE user_id = $who")) {
while($row = mysql_fetch_array($result))
{
$profileText .= $row['text'];
}
?>
<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">
<?php echo $profileText; ?>
</textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
} else {
?>
<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>
<?php echo $profileText; ?>
</textarea><br />
<input type='submit' value='Submit' />
</form>
<?php
}
?>
The basic idea is to add a record if new and update if not. What you can do is use an id to represent the record or -1 if it's a new entry
Something along the lines of:
//Defaults
$recordid=-1;
$name='';
$comments='';
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
//Yes. Get the id
$recordid = $result->id;
//Get the values
$name= $result->name;
$comments= $result->name;
}
<form action="../edit/index.php" method="post" name="formdata">
<input type="hidden" name="recordid" value="<? echo htmlspecialchars($recordid) ?>">
<input type="hidden" name="name" value="<? echo htmlspecialchars($name) ?>">
<textarea name="comments" id="comments"><? echo htmlspecialchars($comments) ?></textarea>
<input type="submit" value="submit"/>
</form>
This way a new form will have a -1 but an existing will have an id.
As an additional point it is very important to sanitize your inputs for SQL and what you output in HTML to stop SQL Injections. For your reference on this:
SQL
Little Bobby Tables
Cross Site Scripting

PHP Form update will not update

I have written an Edit part of my Form but somehow it will not Update the edited Fields. The Code does not give any Errors but it will not update?!
If possible could somebody take a look please?
<?php
include "connect.php";//database connection
if (isset($_GET["id"])) {
$id = intval($_GET["id"]);
if (isset($_POST["edited"]))
{
$update = "UPDATE traumprojekt SET";
$update .= sprintf("quantityProduct='%s', " , mysql_real_escape_string($_POST["quantityProduct"]));
$update .= sprintf("titleProduct='%s', " , mysql_real_escape_string($_POST["titleProduct"]));
$update .= sprintf("informationProduct='%s'", mysql_real_escape_string($_POST["informationProduct"]));
$update .= "WHERE id = '$id'";
mysql_query($update);
}
$sql = "SELECT * FROM `traumprojekt` WHERE id=$id";
$res = mysql_query($sql) or die (mysql_error());
if (mysql_num_rows($res) == 1)
{
$row = mysql_fetch_assoc($res);
?>
<form method="post" action="edit_form.php?id=<?php echo $row["id"] ?>">
ID: <?php echo $row["id"] ?><br />
Quantity: <input type="text" name="quantityProduct" value="<?php echo $row["quantityProduct"] ?>"><br />
Product Title: <input type="text" name="titleProduct" value="<?php echo $row["titleProduct"] ?>"><br />
Product Information: <input type="text" name="informationProduct" value="<?php echo $row["informationProduct"] ?>"><br />
<input type="submit" name="submit" value="Update"><br />
<input type="hidden" name="edited" value="1">
</form>
<?php
}
}
?>

Update multiple rows with radio button check

I am getting the value for the single tsid for each record, however the checked radio button value is not returned in the array, I just get 0? Any help is appreciated.
PHP:
// Set the timesheets to set status approved/rejected
// find out how many records there are to update
$size = count($_POST['tsid']);
// start a loop in order to update each record
$i = 0;
while ($i < $size) {
// define each variable
$tsid = intval($_POST['tsid'][$i]);
$personnelid = intval($_POST['personnel'][$i]);
print "TSID: " . $tsid . "<br>";
print "TSuser: " . $personnelid . "<br>";
if ($tsid > 0 && $personnelid > 0) {
// do the update and print out some info just to provide some visual feedback
$query = "Update timesheets set status='1' where id= '$tsid' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
}
++$i;
}
mysql_close();
HTML:
<input type="hidden" name="tsid[]" value="<?PHP echo $row['id']; ?>">
<li data-role="fieldcontain">
<a href="tsapprove.php?id=<?PHP echo $row['id']; ?>"><p><?PHP echo $row['personnel']; ?></p>
<p><?PHP echo $row['name']; ?></p>
<p class="ui-li-aside"><strong><?PHP echo $row['totalhrs']; ?> H</strong></p>
<fieldset data-role="controlgroup" data-type="horizontal">
<input type="radio" name="personnel[]" id="1" value="<?PHP echo $row['personnel']; ?>" />
<label for="1">Approve</label>
<input type="radio" name="personnel[]" id="2" value="<?PHP echo $row['personnel']; ?>" />
<label for="2">Reject</label>
</fieldset>
</a>
View Details
</li>
Hopefully you can piece this together:
<?
$size = count($_POST['tsid']);
echo "<pre>";print_r($_POST);echo "</pre>";
$i = 0;
while ($i < $size) {
$tsid = $_POST['tsid'][$i];
$pid = $_POST['personnel_'.$i];
print "TSID: " . $tsid . "<br />";
print "TSuser: " . $pid . "<br />";
$i++;
}
?>
<form method="post">
<!--tsid[0] - $i = 0-->
<input type="hidden" name="tsid[]" value="1" />
<input type="radio" name="personnel_0" value="111" />
<input type="radio" name="personnel_0" value="222" />
<!--tsid[1] - $i = 1-->
<input type="hidden" name="tsid[]" value="2" />
<input type="radio" name="personnel_1" value="333" />
<input type="radio" name="personnel_1" value="444" />
<input type="submit" />
</form>
Basically, the way you are returning personnel doesnt really work. So I simplified this a bit, and basically set the radios for personnel differently. Instead of an array, its setting the actual name with the TSID value.
I hard coded 1 and 2, but you would replace with your $row['id'], as well has the number after "personnel_" would be 0..1..2 etc
Hopefully this helps
edit: few issues with code

Categories