I am new at PhP and trying to write a code that will get all emails from table in db and wrtie them into BCC field in email client(I am using Outlook).
Fisrt I have created HTML code. For ex, If selected value is Partneri, then I want do get all emails from table where category is Partner.
<select name="email">
<option value="Uposlenik"> Uposlenici <br/>
<option value="Partner"> Partneri <br/>
<option value="Limari Montazeri"> Limari montažeri <br/>
<option value="Gradjevinske firme"> Građevinske firme <br/>
<option value="Krovopokrivacke firme"> Krovopokrivačke firme <br/>
<option value="Preradzivaci lima"> Preradživači lima <br/>
<option value="Limarske radionice"> Limarske radionice <br/>
<option value="Stovarista-Trgovci"> Stovarišta-Trgovci
</select>
After that I have created php file, and I got no errors. The result I got is only selected value nothnig else shows up.
<?php
$host="localhost"; // Host name
$username="***"; // username
$password="***"; // password
$database="***"; // Database name
$tbl_name="clanovi"; // Table name
$link=mysql_connect("$host", "$username", "$password");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$database");
if (!$db_selected) {
die ('db is not selected : ' . mysql_error());
}
$kategorija=$_POST['email'];
//check post
echo $kategorija;
$query= "SELECT `EMAIL` FROM `clanovi` WHERE `KATEGORIJA`='$kategorija'";
$result=mysql_query($query) or die ("Error, query failed!");
mysql_close($link);
$row=1;
$numrows=mysql_num_rows($result);
$bccfield="Bcc:".mysql_result($result,0,"email");
while($row<$numrows)
{
$email=mysql_result($result, $row,"email");
$bccfiled="," .$email;
$row++;
Print "<a href=mailto:test#test.com?bcc=".$bccfield." /> " ;
}
$bccfield .="\r\n";
?>
Any help would be appreciated. Thanks in advance!
You have a small glitch in your code. It should be $bccfiled.="," .$email;, note the . before the =, otherwise you overwrite the variable content in every iteration of the loop. But even better style would be to store the addresses in an array and implode() them afterwards like this: implode(',',$bccfields).
So the lower part of your script should go something like this:
<?php
// ...
$query= "SELECT `EMAIL` FROM `clanovi` WHERE `KATEGORIJA`='$kategorija'";
$result=mysql_query($query) or die ("Error, query failed!");
while(FALSE!==($row=mysql_fetch_assoc($result))) {
$bccfields[] = $row['EMAIL'];
}
echo sprintf("<a href=mailto:test#test.com?bcc=%s />\n",
urlencode(implode(',',$bccfields)));
?>
Note that I have not tested this, just typed it down. But you should get the idea when you study it.
Try this,
mysql_result($result,0,"EMAIL");
.....^
instead of
mysql_result($result,0,"email");
You should start from $row=0; instead of $row=1;. Otherwise you will ignore the last row retrieved from DB.
Related
I'm in the process of making a web page that's meant to display data that's within a database. The database is stored in MySQL and I'm making the web page in PHP. The PHP code that I have is
<form action="list_projects.php" method="post">
<p>Choose Search Type: <br /></p>
<select name="searchtype">
<option value="partNo">Part Number</option>
<option value="pname">Part Name</option>
<option value="color">Part Colour</option>
<option value="weight">Part Weight</option>
<option value="city">City</option>
</select>
<br />
<p>Enter Search Term: </p>
<br />
<input name="searchterm" type="text" size="20"/>
<br />
<input type="submit" name="submit" value="Search"/>
</form>
<?php
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
$query = "select * from project where ".$searchtype." like '%".$searchterm."%'";
var_dump($query);
$result = mysqli_query($link,$query);
$num_results = mysqli_num_rows($result);
echo "<p>Number of projects found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<p><strong>".($i+1).". Part Number: ";
echo htmlspecialchars(stripslashes($row['partNo']));
echo "</strong><br />Part Name: ";
echo stripslashes($row['pname']);
echo "<br />Part Colour: ";
echo stripslashes($row['color']);
echo "<br />Part Weight: ";
echo stripslashes($row['weight']);
echo "<br />City";
echo stripcslashes($row['city']);
echo "</p>";
}
mysqli_free_result($result);
mysqli_close($link);
?>
but when I run it, I get string(49) "select * from project where projectNo like '%J1%'" Number of projects found: This PHP script is meant to load different projects that's within the database and in a welcome.php script that calls this script connects to the database and it does connect to it correctly.
Looks like you've var dumped the wrong variable. You could try this instead:
$query = "SELECT * FROM project WHERE ".$searchtype." LIKE '%".$searchterm."%'";
$result = mysqli_query($link,$query) or die("Line ".__LINE__." Error found: ".mysqli_error($link)); // If there's an error, it should show here.
Because it's painful, I want to rewrite your code and show you how you should be doing this:
Please note that at the top of your page is a reference to an include file in which you would set your database variable ($link).
<?php
//include "../../reference/to/mysql/login.php";
/***
* The below code block should be in your include file referenced above
***/
$link = mysqli_connect("localhost", "my_user", "my_password", "my_db");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
/***
* End connection block
***/
/***
* Your data is POSTed so it can not be trusted and must at the
* very least be escaped using the below functions.
***/
$searchtype=mysqli_real_escape_String($link,$_POST['searchtype']);
$searchterm=mysqli_real_escape_String($link,$_POST['searchterm']);
$searchterm=trim($searchterm);
/***
* Because your $searchtype is a column reference you need to ensure
* it fits the allowed characters criteria for MySQL columns
***/
$searchtype = preg_replace("/[a-z0-9_]/i","",$searchtype);
Please read the MySQL manual about the allowed characters to use in column names. $ is also allowed but I'm removing that from here because you really should not be using that symbol as a column name character.
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
$query = "select * FROM project WHERE ".$searchtype." LIKE '%".$searchterm."%'";
$result = mysqli_query($link,$query) or die("Line ".__LINE__." Error: ".mysqli_error($link));
$num_results = mysqli_num_rows($result);
echo "<p>Number of projects found: ".$num_results."</p>";
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$i++;
echo "<p><strong>".$i.". Part Number: ";
echo htmlspecialchars($row['partNo']);
echo "</strong><br />Part Name: ";
echo htmlspecialchars($row['pname']);
echo "<br />Part Colour: ";
echo htmlspecialchars($row['color']);
echo "<br />Part Weight: ";
echo htmlspecialchars($row['weight']);
echo "<br />City ";
echo htmlspecialchars($row['city']);
echo "</p>";
}
?>
Hopefully you can see here that I have replaced your for loop with a while loop that does the same thing, taking each row from the database one at a time and outputting it as an array with identifier $row .
I have also used mysqli_fetch_array instead of your fetch_assoc.
I have corrected the spelling mistake in your stripslashes function, but also replaced stripslashes with htmlspecialchars because stripslashes is an old and almost useless renegade function that should not be used with even remotely modern Database interfacing
Your issue is also that this page coded here has not had $link declared for it, the $link idenitifier needs to be set at the top of every page that wants to connect to the database. You need to remember that PHP does not remember standard variables across pages so just because you setup $link in welcome.php does NOT mean that it is known in this page here.
Use or die (mysqli_error($link)); appended to the end of your queries to feedback to you what errors occur.
You must also get into the habit of using PHP Error Reporting to make any headway in solving your own issues.
$link is usually set up in a PHP include file that you simply call at the top of every PHP page that requires it.
IF needed, details about how to connect to MySQLi.
So i was doing our thesis and i need to transfer some values from my sql database to my
here's the sample code:
<tr>
<td id="t" align="center">Subject: <select name="subj">
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("sps_ccp",$con);
$college=$_SESSION['college1'];
$sql="SELECT * FROM subject_db WHERE crs='$college'";
$result=mysql_query($sql,$con);
$count=mysql_num_rows($result);
//echo $count;
for($ctr=0;$ctr<$count;$ctr++)
{
$sql1="SELECT subject FROM subject_db WHERE crs='$college'";
$subj=mysql_query($sql1,$con);
$subj1=mysql_result($subj,$ctr);
echo "<option value=".$subj1.">".$subj1."</option>";
}
?>
</select>
</td>
And also i have this option where i have to get that option value then it'll search through my database and get that value and put it in another option.
here's the sample code:
<tr>
<td id="t">Building: <select name="build">
<option value="hr">HR Building</option>
<option value="pr">PR Building</option>
<option value="gv">GV Building</option>
</select>
</td>
<td id="t">Room: <select name="room">
<?php
if(isset($_POST['build'])){
if($_POST['build']=='hr')
{
$hr = mysql_query("SELECT * FROM hrbuilding");
$h1 = mysql_num_rows($hr);
while(mysql_fetch_array($hr)){
if(h1>0)
{
echo "<option value=".$hr.">".$hr."</option>";
}
}
}
}
?>
</td>
Both didn't worked. It didn't have values on the option box. I did checked my database and I don't think that there are any problems with it. I asked someone on how to work on this but he suggested to use javascript which i really couldn't understand how it works.
Hoping you could help me :) thanks!
hope this may help you
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<select name="sample_s">
<?php
mysql_connect("localhost","root","your_password");
mysql_select_db("db_name");
if(mysql_errno())
die("Database Server is Offline");
$q=mysql_query("SELECT `id`, `opt` FROM `sample`");
if(mysql_num_rows($q)){
while($m=mysql_fetch_assoc($q))
{
echo '<option value="'.$m["opt"].'">'.$m["opt"].'</option>';
}
}
?>
</select>
</body>
</html>
I think you have an error here:
You get the results from query, yet you're calling again the same query but without actually getting the fields (merely the query's resource). There's also a missing quote from value attribute.
To fix:
$db_selected = mysql_select_db("sps_ccp",$con);
$college=$_SESSION['college1'];
$sql="SELECT * FROM subject_db WHERE crs='$college'";
$result=mysql_query($sql,$con);
$count=mysql_num_rows($result);
//echo $count;
while($row=mysql_fetch_assoc($result)) {
echo '<option value="'.$row["subject"].'">'.$row["subject"].'</option>';
}
Also when using sessions in a file, make sure that you're calling session_start and this must be the top position of your file, since it is a header-send call.
Also in your second code block you forgot to put a dollar in front of h1 variable.
EDIT
// very top of file
ini_set("display_errors",1);
error_reporting(E_ALL);
// now, just call your PHP code but in between 2 calls
ob_start();
...call your PHP code here
$buffer = ob_get_clean();
echo $buffer; // what is here? place it so you can see on screen what it says
The first body of code may not have worked because of the missing session_start(); which is required when using sessions. Since it's required to be at the top, you stand at getting an error stating that headers already sent... therefore you will need to either seperate your HTML from PHP, having PHP on top, or placing ob_start(); on top of session_start();
Your second body of code is most likely failing because of this if(h1>0) which should read as if($h1 > 0) you left out the $ sign.
Plus, in your first body of code, you are missing the password parameter in: (if it's not a typo)
$con = mysql_connect("localhost","root");
which should read as:
$con = mysql_connect("localhost","root","password");
Example taken from http://www.php.net/mysql_connect
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
N.B.: Do consider switching to mysqli_* functions. mysql_* functions are deprecated and will be removed from future releases.
I want to show options from my database for users to check, but having trouble getting user's choice.
So, I write two php files,
the first one doing things like: getting data from database, displaying in select option, then submit value by post to and the second php file.
And the second php file just display the recieved value.
Here's the first php file:
<html>
<body>
<form method="post" action="second.php">
<Select name=”select_value”>
<?
//connect to server
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Error " . mysqli_error($con));
$query = "SELECT * FROM MYTABLE" or die("Error in the consult.." . mysqli_error($con));
$result = $con->query($query);
//display result in select option
while ($row = mysqli_fetch_array($result)) {
echo "<Option value=".$row['ENTRY_ID']."> ".$row['ENTRY_NAME']."</Option><br>";
}
mysqli_close($con);
?>
</Select>
</form>
</body>
</html>
And the second php file:
<?
$option = isset($_POST['select_value']) ? $_POST['select_value'] : false;
if($option) {
echo $_POST['select_value'];
} else {
echo "not getting value of select option";
exit;
}
?>
If this works fine, I should see the selected value by the second php file, but I keep recieving my echo "not getting value of select option".
There must be something wrong between select option and my recieving file.
Can someone help?
try this double quotes
<Select name="select_value">
instead of <Select name=”select_value”>
i try to get data from mysql db into html dropdown , i execute the query in PHPmyadmin and its work fine , the result is one record,and all the website is connected with theses details of MYSQL my code is :
<?php
mysql_connect("localhost", "root", "1212") or die("Connection Failed");
mysql_select_db("test")or die("Connection Failed");
$query = "SELECT department_name FROM department";
$result = mysql_query($query);
?>
<label for="department" > Department Name </label>
<select name="departments" >
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['field'];?>"> <?php echo $line['field'];?> </option>
<?php
}
?>
</select>
the output is drop-down with one empty record , any one can help me in that ?
First required statement: mysql_ is deprecated. mysqli_ should be used instead.
Second ...
Did you try $line['department_name'] instead of $line['field'] ?
Well first of all you should print the results of the query to ensure the array structure is what you think it is.
This would have shown you that there is no column in the result set named field as you seem to believe due to this line of code:
<option value="<?php echo $line['field'];?>"> <?php echo $line['field'];?> </option>
As to why you only get one option, my first bit of advice will probably shed some light on said issue as well.
I am newbie to php.I have coded auto-complete text box using php,and i have a submit button.i have not given form action.
This is the HTML form code that i used for autocomplete textbox.this autocomplete textbox selects the value
<form method="post" autocomplete="off">
<p>
<b>Theater Name</b> <label>:</label>
<input type="text" name="theater" id="theater" />
</p>
<input type="submit" value="Submit" />
</form>
I have another php function that retrieves the values based on where clause.in the where statement i want to use selected value from form.
for ex: select address from theaters where theater_name ="form value"
How to use the form value in php function?can any one help me?
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("theaterdb", $con);
$result = mysql_query("SELECT * FROM theter
WHERE theater_name="<!-- This could be value that we get after clicking submit button-->);
while($row = mysql_fetch_array($result))
{
echo $row['thearer_name'];
echo "<br />";
}
?>
Thanks in advance......
You could get the value from $_POST by $_POST['theater'].
And note, you should not use this value directly in the sql, you need to escape it to prevent sql injection.
$theater = mysql_escape_string($_POST['theater']);
$result = mysql_query("SELECT * FROM theter WHERE theater_name='$theater'";
Last, you could take a look at PDO, which is suggested over the old mysql_* functions.
First, change your submit button code to the following:
<input name="submit" type="submit" value="Submit" />
Now, this is the code you should use for the query:
<?php
if (isset($_POST['submit'])) {
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("theaterdb", $con);
$result = mysql_query("SELECT * FROM theater
WHERE theater_name='" . mysql_real_escape_string($_POST['theater']) . "'");
while($row = mysql_fetch_array($result))
{
echo $row['theater_name'];
echo "<br />";
}
}
First, I check that the user submitted the form. Then, I escape the data he has submitted and inserting it into your query.
* NOTE: All of what I've wrote is based on the assumption that the code is executed after the form is submitted.
* ANOTHER NOTE: You should read about using PDO rather than MYSQL functions.
First and foremost, try using mysqli instead of mysql (mysqli_query, mysqli_connect). There are numerous security / speed advantages to using it and it has pretty much the exact same functionality.
While the above answers mention using $_POST['theater'] (the name of your input), be SURE to escape your post before putting it into your query.
$con = mysqli_connect("localhost","root", "YOUR PASSWORD HERE", "YOUR DATABASE HERE");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
// No need for this, please see the updated mysqli_connect as the 4th parameter selects your DB
//mysqli_select_db("theaterdb", $con);
// Please notice the last parameter of the mysqli_real_escape_string is your Input's POST
$query = "SELECT * FROM theater WHERE theater_name=".mysqli_real_escape_string($con, $_POST['theater']);
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo $row['thearer_name'];
echo "<br />";
}
$_POST["your_variable_name"] // for POST
$_GET["your_variable_name"] // for GET
For in-depth information please go to: http://www.php.net/manual/en/language.variables.external.php