PHP and SQL Server Express to retrieve and show data - php

I am looking to take a PHP page to retrieve data based on the selection from a drop down list, then show the results based on that selection. I am not even sure where to begin except my connection to the database. I do also know that I have to have a query statement, like I would in SQL, which here is a little bit of that:
$sql = "SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = 'bs1441'";
The bs1441 is just an example of one option that would be in the drop down list. I am not sure what I would put there for it to put in there automatically from the list.
Thanks for the help in advance. Sorry if there is not enough information to go on, but not sure what even would be needed at this point.
EDIT:
This is what I have so far:
<form method="get" action="getlog.php">
<table width="300" border="0">
<tr>
<td> Forte ID:</td>
<td><select id="ForteID" name="ForteID">
<option value="nc4682">nc4682</option>
<option value="bs1441">bs1441</option>
<option value="sp3212">sp3212</option>
</select></td>
</tr>
</table>
<input type="submit" name="getLog" value="Get Log">
</form>
</head>
<body>
</body>
</html>
<?php
$serverName = 'SRB-Nick_Desktop\SQLEXPRESS';
$connectionInfo = array('Database'=>'cslogs', 'UID'=>'cslogslogin', 'PWD'=>'123456');
$connection = sqlsrv_connect($serverName, $connectionInfo);
$result = sqlsrv_query( $connection,
'SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM Logs
WHERE (ForteID = $ForteID)',
array($ForteID));
while($row = sqlsrv_fetch_array($result))
{
echo($row['ForteID'] . ', '.
$row['Disposition'] . ', '.
$row['appNumber'] . ', '.
$row['Finance_Num'] . ', '.
$row['Num_Payments'] . ', '.
$row['ACH_CC'] . ', '.
$row['Notes'] . ', '.
$row['Date']);
}
sqlsrv_close( $connection);
?>
Then when I look at the page it throws this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\cslogs\getlog.php on line 46
Line 46 is this line:
echo($row['ForteID'] . ', '.
Let me know if that helps!

A couple steps here:
First you need to submit your form with the selection in. I'm not going to go over form submission here but look into it.
once you submit the form you will need to get the value of the drop down and assign it to a variable.
$value= $_POST['value'];
Note: This is a basic example so I didnt add in regex or anything like that.
Once you have your variable ($value) you can then put it in your SQL
$sql = mssql_query($dbc,"SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = '$value'") or die("Query Error " . mssql_get_last_message());
So here we are processing the query. $dbc is the variable that I chose to represent my database connection and the "or die" part will let me know if the query is valid or not.
Once you have a working query you can then summon the data pulled into an array:
while ($row = mssql_fetch_array($sql)) {
And then you need to assign the results of your query to a variable.
$result1 = $row["RESULT1"];
$result2 = $row["RESULT2"];
The capital words are the titles of the columns in your sql table. After you have them assigned to variables you can do whatever you want to them provided they are inside the while loop.
$value= $_POST['value'];
$sql = mssql_query($dbc,"SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = '$value'") or die("Query Error " . mssql_get_last_message());
while ($row = mssql_fetch_array($sql)) {
$result1 = $row["RESULT1"];
$result2 = $row["RESULT2"];
echo $result1;
echo $result2;
}

Related

Get values checked

I am having trouble in getting checked values checked in form. I was trying to use the same function as I have used to insert values to print all values in edit form, and which are in other table inserted to mark them checked.
Function to insert values in database table in insert form and it works.
function emarketing_usluge(){
$link = new mysqli("localhost", "xxx", "xxx", "xxx");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT * FROM `jos_ib_emarketing_oprema` order by OpremaId asc ");
while($record = mysqli_fetch_array($sql)) {
echo '<input type="checkbox" name="usluge[]" value="'.$record['OpremaId ']. '">' . $record['OpremaNaziv'] . ' <br/><br/> </input>';
}
}
In this function I get list of all services and place them in checkboxes.
Now I want to edit form, and display all values that are checked by using same function.
First I make query to get values, I am using here pdo but for funcion files I have used mysqli.
Form for editing!
$sql_oprema = "SELECT a.Partner, a.OpremaId, a.Oprema, b.OpremaNaziv
FROM jos_ib_emarketing_stavke_oprema a
join jos_ib_emarketing_oprema b
on OpremaId = b.Oprema
WHERE a.Partner= $id";
$oprema = $conn->query($sql_oprema);
$row = $oprema ->fetch();
<div class="col-xs-6">
<input type="checkbox" id="oprema" onclick="Exposeoprema()">Oprema<br>
<div id="Scrolloprema" style="height:150;width:200px;overflow:auto;border:1px solid blue;display:none">
<?php
while($row = $oprema ->fetch()) {
$data='<input type="checkbox" name="oprema[]" value="'.$row["Oprema"].'"';
if(isset($row['Oprema'])) {//field in the database
$data.=' checked="checked';
}
$data.='">'. $row["OpremaNaziv"] .'</br>';
}
emarketing_oprema($data);
?>
</div>
</div>
I am trying print all service values by using function, but the ones that are checked they need to have check mark. I am getting problem and could not figure it out how to solve it.
Looking back to your SQL query, I don't see an extraction of checked field, you are not selecting it. So there is never going to be a $row['checked'] element of your query.
You should add:
$sql_oprema = "SELECT a.checked, a.Partner, a.OpremaId, a.Oprema, b.OpremaNaziv
FROM jos_ib_emarketing_stavke_oprema a
join jos_ib_emarketing_oprema b
on OpremaId = b.Oprema
WHERE a.Partner= $id";

PHP form unable to update database

Hi guys I'm having trouble with my PHP code. Unable to update the database when I submit the form. I'm trying to update the new price.
Here's my PHP code:
<?php
if(isset($_POST['update']))
{
# $db = new mysqli('localhost','XXXX','XXXX','XXXX');
if(! $db )
{
die('Could not connect: ' . mysqli_error());
}
$price = $_POST['price'];
$sql = "UPDATE bookprice ".
"SET price = price " ;
mysqli_select_db('books');
$retval = mysqli_query( $sql, $db );
if(! $retval )
{
die('Could not update data: ' . mysqli_error());
}
echo "Updated Price successfully\n";
mysqli_close($db);
}
else
{
?>
Form code:
<form method="post">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>
<input name="update" type="submit" id="update" value="Update Price">
<input name="price" type="text" id="price">
</td>
</tr>
</table>
</form>
Still in the process of grasping PHP. Any form of help is greatly appreciated!
You're not using the $price variable to set the price column to.
Use "SET price = $price " ;
or inside quotes "SET price = '$price' " ;
What you're doing right now is "set the price column equals price column" instead of the intended value taken from the POST variable $price. More on this at the end of my answer under Footnotes.
Another thing:
$retval = mysqli_query( $sql, $db );
you need to reverse the query and DB connection:
$retval = mysqli_query( $db, $sql );
In mysqli_, the connection comes first, then the query's variable.
Plus, use:
$db = new mysqli('localhost','XXXX','XXXX','books');
You're using all four parameters in your DB connection, so you can drop:
mysqli_select_db('books');
since you're not doing anything with it, and simply add books as the DB's parameter.
Using the fourth parameter with the DB's name, is the same as using mysqli_select_db with the DB's name and connection variable, which is something you are not using.
Read the manual http://php.net/manual/en/mysqli.select-db.php
You also have a missing closing brace in
else
{
?>
if you don't have anything after that, do:
else
{
echo "Fail";
}
?>
Footnotes:
If your price contains a dollar sign, or a dot or mix of those, or something else that SQL does not agree with (which am under the impression it could), you will need to wrap it in quotes:
$sql = "UPDATE bookprice SET price = '$price' " ;
or
$sql = "UPDATE bookprice SET price = '".$price."' " ;
If your column is an int type, then you can use
$sql = "UPDATE bookprice " . "SET price = ".$price;
remove #
$db = new mysqli('localhost','XXXX','XXXX','XXXX');
and update the query
$sql = "UPDATE bookprice ".
"SET price = ".$price ;
Give this a try:
<?php
if($_POST['update']){
$db = new mysqli('localhost','XXXX','XXXX','XXXX'); // remove '#'
if(!$db){
die('Could not connect: ' . mysqli_error($db)); // Needs the database connection
}
$price = $_POST['price'];
$sql = "UPDATE `bookprice` SET `price` = '$price'"; // Use the variable $price
// mysqli_select_db('books'); // This should already be set in the new mysqli();
$retval = mysqli_query($db, $sql); // Turn this around;
if(!$retval) {
die('Could not update data: ' . mysqli_error($db)); // needs the database connection
} else {
echo "Updated Price successfully\r\n"; // \r\n will always work \r or \n alone will not always work
}
mysqli_close($db);
}
else {
echo 'There was no post';
}
?>
HTML:
<form action="" method="post">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>
<input name="update" type="submit" id="update" value="Update Price">
<input name="price" type="text" id="price">
</td>
</tr>
</table>
</form>
Links:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.query.php
http://nl3.php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/function.number-format.php (since you are working with a price this may come in handy)
You should also consider the use of mysqli_real_escape_string() so:
$price = mysqli_real_escape_string($db, $_POST['price']);
Well actually if you concat your queries with $parameter directly, it opens up a security risk
$price = $_GET["price"] (from the URL)
$price = $_POST["price"] (from the FORM Post)
UPDATE bookprice SET price = '$price'
You should try using prepared statements like
Update bookrprice set price = :price
or
Update bookrprice set price = ?
and then create a associate key value pairs to security and pass it in to your query. This is why it is not recommend to use mysql_query and rather mysqli or PDO methods.
then your would pair the above statement by
execute(array(":price"=>$price))
or
execute(array($price))

insert value from drop down box to the database

I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";

Search Form Ability To Ignore Blank Fields

I have made a HTML search form which creates a query to a MySql database based on the contents of a form. What I would love to do is ignore the search parameter if the user leaves that specific form field empty. There are lots of answers online, especially on this website, but I can't get any of them to work.
I have stripped down my code as much as possible to paste into here:
The HTML input:
<form action="deletesearchresults.php" method="GET">
<p><b>First Part Of Postcode</b>
<input type="text" name="searchpostcode"></b> </p>
<p><b>Category</b>
<input type="text" name="searchfaroukcat"></b>
<input type="submit" value="Search">
</p>
</form>
The PHP results display:
<?php
mysql_connect("myip", "my_username", "my_password") or die("Error connecting to database: ".mysql_error());
mysql_select_db("my_db") or die(mysql_error());
$sql = mysql_query("SELECT * FROM
GoogleBusinessData
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]' LIMIT 0,20");
while($ser = mysql_fetch_array($sql)) {
echo "<p>" . $ser['BusName'] . "</p>";
echo "<p>" . $ser['PostcodePostalTown'] . "</p>";
echo "<p>" . $ser['PostcodeArea'] . "</p>";
echo "<p>" . $ser['FaroukCat'] . "</p>";
echo "<p> --- </p>";
}
?>
This works great until I leave one field blank, in which case it returns no results as it thinks I am asking for results where that field is empty or null, which I don't wat. I want all of the results where that form field is empty.
I tried combining a like % [myfeild] % etc but I only want the results to display exactly what is on the field and not just the ones that contain what is in the field, for example searching for the postcode "TR1" would return results for TR1, TR10, TR11 etc.
I believe I may need an array but after 3 days of trying, I just don't know how to get this done.
Any help would be amazing.
edit: Also, I will be adding up to ten fields to this form eventually and not just the two in this example so please bear this in mind with any suggestions you may have.
try using isset()
example
if(isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]'";
}elseif(isset($_GET[searchpostcode]) && !isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]'";
}elseif(!isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE FaroukCat = '$_GET[searchfaroukcat]'";
}else{
$fields = "";
}
$sql = "SELECT * FROM
GoogleBusinessData $fields
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull LIMIT 0,20";
You do however need to escape your $_GET variables however i would highly recommend using PDO/mysqli prepared statements http://php.net/manual/en/book.pdo.php or http://php.net/manual/en/book.mysqli.php
or try a foreach loop
foreach($_GET as $keys=>$value){
$values .= $keys."='".$value."' and";
}
$values = rtrim($values, " and");
if(trim($values) != "" || trim($values) != NULL){
$query = "WHERE ".$values;
}else{
$values = "";
}
$sql = "SELECT * FROM `test`".$values;

sending multiple records to MySQL from multiple select box

I'm trying to insert multiple rows into a MySQL table depending on the number of options selected from a multiple select box. currently it is inserting one row (regardless of how many options are selected) but the 'strategyname' column is empty each time.
Any ideas on how to insert multiple rows and why the values of the options aren't being sent to the table?
Here is the form:
<form method="POST" action="update4.php">
<input type="hidden" name="id" value="1">
<p class="subheadsmall">Strategies</p>
<p class="sidebargrey">
<?php
$result = mysql_query("SELECT strategyname FROM sslink WHERE study_id = '{$_GET['id']}'");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategyname = $row['strategyname'];
echo $strategyname.'<br />';
}
?>
<p class="subheadsmall">Add a strategy... (hold down command key to select more than one)</p>
<select name="strategylist" multiple="multiple">
<?php
$result = mysql_query("SELECT * FROM strategies");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategylist = $row['name'];
$strategyname = htmlspecialchars($row['name']);
echo '<option value="' . $strategylist . '" >' . $strategyname . '</option>' . '\n';
}
?>
</select>
</p>
<input type="submit" class="box" id="editbutton" value="Update Article">
</form>
And this is what sends it to the database:
<?php
$id=$_POST['id'];
$test=$_POST['strategylist'];
$db="database";
$link = mysql_connect("localhost", "root", "root");
//$link = mysql_connect("localhost",$_POST['username'],$_POST['password']);
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link) or die("Select Error: ".mysql_error());
//for($i=0;$i<sizeof($_POST["test"]);$i++)
//{
//$sql = "insert into tbl_name values ($_POST["test"][$i])"; }
//sql = "INSERT INTO table_name VALUES ('" . join(",",$_POST["test"]) . "')";
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) VALUES ('$id','" . join(",",$_POST["strategylist"]) . "')")or die("Insert Error: ".mysql_error());
mysql_close($link);
print "Record added\n";
?>
Couple of points:
your select needs to be named strategylist[] in order to tell PHP that it will contain an array rather than a single value
Your insert code then needs to iterate over that array, creating a new insert for each element it contains, unless (as it seems) you want all those options to be concatenated into a single row's field.
At the moment, your form only returns a single option (from PHP's perspective), so it's only going to insert a single row.
To iterate over the array, use something like this:
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
Two things:
If you view the source of page with the multiple select in it, can you see the <option value="something"> lines there? Are the values empty? It seems strange to me that at the top of your file you are using $row['strategyname'] and later you are using $row['name']. I suspect this may be the cause of the empty StrategyName column.
To handle multiple selections, you should specify the select tag as
<select name="strategylist[]" multiple="multiple">
The extra [] tells PHP to form an array with all of the selections in it. You can then loop over the array like:
$strategylist = $_POST['strategylist'];
for ($i = 0; $i < count($strategylist); $i++) {
$strategyname = $strategylist[$i];
// Insert a record...
}
// first you need to define your output as one variable if you don't like the loop
if($_POST){
$sum = implode(", ", $_POST[select2]);
echo $sum.".";
}
// the variable sum is the one you are seeking for you can insert it to the database
// if you want to enter every peiece of the array in a new field you should use
// different select names

Categories