Adding check in while loop entry - php

Here in this code I am accepting data as an array and inserting it in the database. As I am using while loop I am having multiple input fields with same name as you can see in the HTML code below. What I want to do is, I want to add a check that if two fields are same then echo error saying two fields cannot be the same else insert the data. I could do it if there were two different input fields for the data like if($field1 == $field2){ echo "Error!"; else insert data. But here the field is only one with is giving multiple fields in a while loop. How can I add this check?
HTML form code:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php while($pro = $priq->fetch()){ extract($pro); ?>
<div class="row tbpad">
<div class="col-sm-3 col-xs-6">
<p><i class="fa fa-caret-right"></i> <?php echo $bk_title; ?></p>
</div>
<div class="col-sm-1 col-xs-1">
<div class="form-group">
<input type="text" class="form-control" name="priority[]" value="<?php echo $pr_priority; ?>">
<input type="hidden" class="form-control" value="<?php echo $bk_id; ?>" name="bkid[]">
</div>
</div>
</div>
<?php } ?>
<input type="submit" class="btn btn-orange" value="Set Priority" name="priority">
</form>
PHP code:
if(isset($_POST['priority'])){
$priority = (!empty($_POST['priority']))?$_POST['priority']:null;
$bkid = (!empty($_POST['bkid']))?$_POST['bkid']:null;
$iNumSets = count($priority);
for($i = 0; $i < $iNumSets; $i++){
$str = "INSERT INTO priorities(pr_book, pr_by, pr_priority)
VALUES('$bkid[$i]', '$sess', '$priority[$i]')";
$res = $PDO->prepare($str);
$res->execute();
if($res){
echo '<script>alert("Priority added successfully!");window.location = "view-order.php";</script>';
}else{
echo '<script>alert("Server Error! Please try back later.");window.location = "add-order.php";</script>';
}
}
}

Since $priority is an array which you get from $_POST['priority'], you could do the following:
$num_original = count($priority);
$num_unique = count(array_unique($priority));
if ($num_original != $num_unique) {
echo "One or more item were idendical!";
}
Also make sure you use mysql_real_escape_string() or similar methods on your $_POST input before you pass it into the SQL query. Otherwise your code is vulnerable to SQL injections!

Related

Trying to send info to my database from a select tag

Been trying to get this PHP to send to my database but for some reason it won't work but it isn't giving me any errors either. The code probably isn't the prettiest only been working on PHP for 6 months so any help is much appreciated.
<form method="POST">
<div class="form-group">
<label for="exampleFormControlSelect1">Send Message to: </label>
<select class="form-control" id="slectrecipient" name="recipient">
<?php
include("conn.php");
$info = "SELECT FirstName, SecondName, id FROM PT_accounts WHERE NOT id='$accountid'";
$result4 = $conn->query($info);
if(!$result4){
echo $conn->error;
}
while($row4 = $result4->fetch_assoc()){
$recipientfirst = $row4['FirstName'];
$recipientsecond = $row4['SecondName'];
$recipientid = $row4['id'];
echo "<option value='$recipientid'> $recipientfirst $recipientsecond</option>";
}
if(isset($_POST['messagetext'])){
$currentdate = date("Y-m-d H:i:s");
$messagetext = $_POST['messagetext'];
$recipid = $_POST['recipient'];
echo $currentdate;
echo $messagetext;
echo $recipid;
$messageinsert = "INSERT INTO PT_Messages (SenderID, RecipientID, Date, Message)
VALUES ('$accountid', '$recipid', '$currentdate', '$messagetext') ";
$result5 = $conn->query($messageinsert);
if(!$result5){
echo $conn->error;
}else{
echo "<p> $messageinsert</p>";
echo "<p>Message Sent!</p>";
}
}
?>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Message :</label>
<text class="form-control" id="messagetext" rows="3"></textarea>
</div>
<input type="submit" class="btn btn-primary btn-sm" value="Send">
</form>
I know there's two $row and $results but I've altered these in my actual to be different so I know that's not the issue. I'm unsure if it's the select tag with the option value that isn't written correctly. Or if I have to somehow set the dropdown menu selection as a PHP variable to then be sent to the database?
Thanks to user3783243
I didn't name the textarea but had set it as an id.
<input type="text" class="form-control" name="messagetext" id="messageid" rows="3">
I had it as id="messagetext"

View comma separated values of one column in multiple rows or in multiple values

I am creating a shopping website in which I have saved multiple values in one column in my database.
The column name is "availablesize" and the stored values are "S,M,L,XL".
Now I want to view these three values in separate rows.
Here's my code:
<div> <!-- Added by edit -->
<div> <!-- Added by edit -->
<?php
require_once 'dbconfig.php';
if(isset($_GET['id']) && !empty($_GET['id']))
{
$id = $_GET['id'];
$stmt = $DB_con->prepare('SELECT productid,productname,availablesize FROM products WHERE productid=:uid');
$stmt->execute(array(':uid'=>$id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
extract($row);
}
else
{
header("Location: index.php");
}
?>
<input type="radio" id="red" name="requiresize" value="<?php echo $availablesize;?>" checked>
<label for="red"><span class="sizespan"><?php echo $availablesize;?></span></label>
</div>
<div>
<input type="radio" id="blue" name="requiresize" value="<?php echo $availablesize;?>">
<label for="blue"><span class="sizespan"><?php echo $availablesize;?></span></label>
</div>
<div>
<input type="radio" id="black" name="requiresize" value="<?php echo $availablesize;?>">
<label for="black"><span class="sizespan"><?php echo $availablesize;?></span></label>
</div>
<div>
<input type="radio" id="black" name="requiresize" value="<?php echo $availablesize;?>">
<label for="black"><span class="sizespan"><?php echo $availablesize;?></span></label>
</div>
</div>
Not sure why multiple explodes were listed in previous answer/comment. Seems like unnecessary redundant use of a function call.
<?php
$sizes = explode("," , $availablesize);
$small = $sizes[0];
$med = $sizes[1];
$large= $sizes[2];
$xlarge = $sizes[3];
Now, the variables listed above will contain "S", "M", "L", and "XL".
OR, you could simply display:
<?php echo $sizes[0]; ?>
<?php echo $sizes[1]; ?>
<?php echo $sizes[2]; ?>
<?php echo $sizes[3]; ?>
Just a matter of preference in how you want to display them. By creating specific variables, you'd be able to use them elsewhere if you want.
<?php echo explode(',', $availablesize)[0];?> = S
<?php echo explode(',', $availablesize)[1];?> = M
<?php echo explode(',', $availablesize)[2];?> = S
<?php echo explode(',', $availablesize)[3];?> = XL

Retrieve all row but the first record is missing

$query = "SELECT * FROM abc";
if ($result = $db->query($query)) {
$row = $result->fetch_assoc();
while ($row = $result->fetch_assoc()) {
$data[] = array("a"=>$row["a"],
"b"=>$row["b"],
"c"=>$row["c"],
"d"=>$row["d"]
);
}
$result->close();
}
$db->close();
<?php foreach ($data as $row) { ?>
<form action="">
<div class="col-lg-3">
<input type="text" value="<?php echo $row['a'] ?>"/>
</div>
<div class="col-lg-3">
<input type="text" value="<?php echo $row['b'] ?>"/>
</div>
<div class="col-lg-3">
<input type="text" value="<?php echo $row['c'] ?>"/>
</div>
<div class="col-lg-3">
<input type="text" value="<?php echo $row['d'] ?>"/>
</div>
</form>
<?php } ?>
Above is the exact code that I used to retrieve all the row in a table. The strange part is that I have 5 row and it only show 4. The first row is missing. I wonder why.
In your code, you're calling $row = $result->fetch_assoc(); just before starting your while loop. This line is "consuming" your first raw and when you're entering in the loop, you move the cursor to the second row by calling this same method a second time.
The condition of the while loop is executed BEFORE the content, here you'll find more info about PHP While loop
To fix your code, remove this first line.

How to Post all the values

while($row = mysql_fetch_array($result))
{
$a=$row['diagnosis'];
$b=$row['icd_code'];
echo' <div class="form-group"><div class="col-lg-8">
<input class="form-control" type="text" name="disease" value="'.$a.'">';
echo '</div>
<div class="col-md-11 pull-right mrgT10">
<input type="text" class="tags" name="icd" value="';echo $b.'" />
</div>
</div>'; } ?>
This is my php coding.When i process the form using anotherpage php with the following code
<?php
include('connect.php');
if(isset($_POST['submit']))
{
echo $disease=$_POST['disease'].'<br/>';
echo $icd=$_POST['icd'];
}?>
It will get only the last value like this.
MONOPLEGIA
447637006
Is there anyway to get all the values.Any suggestion or tips would be appreciated.
You can make it your textfields name as name="disease[]" , name="icd[]" instead of name="disease" and name="icd[]"
and you can retrive like
$diseases=$_POST['disease'];
foreach($diseases as $key=>$disease){
echo $disease;
echo $icd=$_POST['icd'][$key];
}
Also, change this value="';echo $b.'" into value="'.$b.'"
try this :
while($row = mysql_fetch_array($result))
{
$a=$row['diagnosis'];
$b=$row['icd_code'];
echo' <div class="form-group"><div class="col-lg-8">
<input class="form-control" type="text" name="disease[]" value="'.$a.'">';
echo '</div>
<div class="col-md-11 pull-right mrgT10">
<input type="text" class="tags" name="icd[]" value="';echo $b.'" />
</div>
</div>'; } ?>
and call the value at other php :
<?php
include('connect.php');
if(isset($_POST['submit']))
{
foreach($_POST['disease'] as $a=>$key){
echo $disease=$a[$key].'<br/>';
echo $icd=$_POST['icd'][$key];
}
}?>
hope this can help you.
You need to pass array so that you will get all values of result and serialize it and submit it to another form.
on next page you need to unserialize the array and you will get the whole array.
please try this code
<?php
while ($row = mysql_fetch_row($result)){
$a[] = $row[3];
$b[] = $row[4];
}
$var1 = serialize($a);
$var2 = serialize($b);
?>
**another_page.php**
<?php
print_r($_REQUEST);
$var1 = unserialize($_POST['b']);
print_r($var1);
die();
Hope U will get some thing...

HTML form $_POST not being retrieve and set into PDO QUERY

I decided to leave in all the code to make it less confusing to those who see this.
On line #57, the only form on this page, I'm trying to $_POST the id that equals the post_iD.
Everything uploads correctly to MySQL besides the post_iD.
I always get a Notice: Undefined index: post_iD on $post_iD = $_POST['post_iD']; inside the if(isset($POST['comment'])).
I'm sure the issue is with how I'm trying to retrieve the post_iD inside the form, and not any issues with the PDO but html as PDO the data is being inserted correctly besides the post_iD which I have mentioned.
I'm using post_iD to loop posts from database, it works besides inside the form, any enlightenment with this issue?
Code Below.
if(isset($_POST['comment'])){
$comment = $_POST['comment'];
$post_iD = $_POST['post_iD'];
$data = $Wall->Insert_Comment( $uiD, $post_iD, $comment, $_SERVER['REMOTE_ADDR'] );
}
if ( $updatesarray ){
foreach ($updatesarray as $data){
$post_iD = $data['post_iD'];
$orimessage = $data['message'];
$message = tolink(htmlcode($data['message']));
$time = $data['created'];
$mtime = date("g:i", $time);
$username = $data['username'];
$uploads = $data['uploads'];
$uiD = $data['uid_fk'];
?>
<div class="wrap">
<div class="item" id="stbody<?php echo $post_iD;?>">
<div class="loop-post">
<div class="loop-post-content">
<div class="loop-post-image">
<a href="" class="post-link">
<?php
if ($uploads){
$s = explode(",", $uploads);
foreach ($s as $a){
$newdata = $Wall->Get_Upload_Image_Id($a);
if ($newdata) echo "<a href='uploads/" . $newdata['image_path'] . "' rel='facebox'>
<img src='uploads/" . $newdata['image_path'] . "' width='520' height='245' class='imgpreview attachment-top_story_post wp-post-image' /></a>";
}
echo "</div>";
}
?>
</a>
</div>
<div class="loop-post-byline">By <a rel="author" title="Posts by Emil Protalinski" href=""><?php echo $username;?></a>
<span class="date"> — <?php echo $mtime;?></span>
</div>
<a class="post-link">
<?php echo clear($message);?>
</a>
<div class="post_comment">
<?php $x=1; include_once 'load_comments.php'; ?>
<div class="commentupdate" id="commentbox<?php echo $post_iD;?>">
<div class="stcommentimg">
<img src="<?php echo $photo;?>" class="small_face">
</div>
<div class="stcommenttext">
<form method="POST" action="">
<textarea name="comment" class="comment" id="<?php echo $post_iD;?>" value="<?php echo $post_iD;?>"></textarea> #57
<input type="submit" value="comment">
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php } } else echo '<h3 id="noupdates">No Updates!</h3>';?>
You are never actually setting the post_iD variable anywhere. If you want to use it in the $_POST array you need to set it in the form first.
<form method="POST" action="">
<input type="hidden" name="post_iD" value="<?php echo $post_iD; ?>" />
<textarea name="comment" class="comment" id="<?php echo $post_iD;?>" value="<?php echo $post_iD;?>"></textarea> #57
<input type="submit" value="comment">
</form>
You need to do this...
<textarea name="comment" class="comment" id="comment-<?php echo $post_iD;?>"></textarea>
<input type="hidden" id="post_iD" name="post_iD" value="<?php echo $post_iD;?>" />
Cuz youre never passing the post_iD anywhere....this will pass it in hidden form...
And the value for your textarea wont be $post_iD, it will likely be a comment/post of some type....I assume you just had that for debugging

Categories