I am very new to PHP (only been doing it since September so I apologise if this seems like a silly question, I'm very stuck and can't work out the answer!) and cannot work out why my error message does not display when a user submits the form when it is empty.
This is my code:
<?php
$salonid = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error($db_server));
$db_status = "not connected";
}else{
//Capture form data, if anything was submitted
if (isset($_GET['salonid']) and ($_GET['salonid'] != '')){
$salonid = clean_string($db_server, $_GET['salonid']);
//If connected, get Salons from database and write out
mysqli_select_db($db_server, $db_database);
$query = "SELECT ID, salon_name, address, postcode, telephone, email, website FROM salon WHERE ID=$salonid";
$result = mysqli_query($db_server, $query);
if (!$result) die("Query failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_result .= "<h2>" . $row[ 'salon_name'] . "</h2>";
$str_result .= "<p>" . $row['address'] . "</p>";
$str_result .= "<p>" . $row['postcode'] . "</p>";
$str_result .= "<p>" . $row['telephone'] . "</p>";
$str_result .= "<p>" . $row['email'] . "</p>";
$str_result .= "<p>" . $row['website'] . "</p>";
}
mysqli_free_result($result);
}else{
$str_result = "<h2>No salon selected</h2>";
}
}
echo $str_result;
?>
<?php
if(trim($_POST['submit']) == "Submit comment"){
//Get any submitted comments and insert
$comment = clean_string($db_server, $_POST['comment']);
if ($comment != '') {
$name=$_FILES['photo']['name'];
if ($name = "") $error .= "<p class='error'>You must upload an image!</p>";
$originalname=$_FILES['photo']['name'];
$type=$_FILES['photo']['type'];
if ($type=="image/jpeg") $type=".jpeg"; //if true change
else if ($type=="image/jpg") $type=".jpg";// if not true check this one
else if ($type=="image/png") $type=".png";
$name=uniqid() . $type;
$path="images/" . $name;
$tempname=$_FILES['photo']['tmp_name'];
$size=$_FILES['photo']['size'];
//Error checking
if ($size >1000000) $error .= "<p class='error'>Your image file is to big, it have to be less than 200 mb</p>";
if ($error=="") {
if (move_uploaded_file($tempname, $path)){
$uploadquery="INSERT INTO comments (comment, imagename, salonID, userID) VALUES ('$comment', '$path', $salonid, ". $_SESSION['userID'].")";
mysqli_query($db_server,$uploadquery) or die ("Insert failed " . mysqli_error($db_server) . " " . $uploadquery);
$message= "<h2>Thanks for your comment!</h2><p>Your upload was succesful</p>";
}
}
}
}
//Print out existing comment
$query = "SELECT * FROM comments JOIN users ON comments.userID = users.ID WHERE salonID=$salonid";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while ($row = mysqli_fetch_array($result)){
$str_comments .="<h2>" . $row['Username'] ."</h2>";
$str_comments .= "<p>" . $row['comment'] . "</p>";
$str_comments .="<img src='" . $row['imagename'] ."' />";
}
mysqli_free_result($result);
?>
<div id="form">
<table><form id='review' action='salonpage.php?salonid=<?php echo $salonid; ?>' method='post' enctype='multipart/form-data'>
<th><h2> Do you want to review the service you recieved?</h2></th>
<tr><td><textarea name="comment" rows="6" cols="40">Write something here!</textarea></td></tr>
<tr><td><input type='file' name='photo' accept='image/jpg, image/jpeg, image/png'/></td></tr>
<br/>
<tr><td><input type='submit' id='submit' name='submit' value='Submit comment' /></td></tr>
</form></table>
<?php echo $message;
echo $str_comments; ?>
</div>
<?php mysqli_close($db_server); ?>
if ($comment != '') {
$name=$_FILES['photo']['name'];
if ($name = "") $error .= "<p class='error'>You must upload an image!</p>";
$originalname=$_FILES['photo']['name'];
in this code you are using
$name = ""
which is an assignment operator you need to use comparison operator within if condition either ==or ===
I think, you are talking about $error, if i am correct then you did not echo $error variable in your above mention code. One more thing add else part on if block "if ($comment != '')" else {$error.="no comment entered" }
Related
I am making e-commerce site and add to basket script not doing anything
I expect it to insert data into shopping basket from products page that is working perfectly fine. Please have a look and help me figure it out.. it is not giving any syntax error or parse error it just dont do anything and when I click buy it just redirect me to homepage
<?php
error_reporting(E_ALL);
session_start();
require("db.php");
require("functions.php");
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$prodres = mysqli_query($prodsql);
$numrows = mysqli_num_rows($prodres);
$prodrow = mysqli_fetch_assoc($prodres);
if($numrows == 0)
{
header("Location: " . $config_basedir);
} else {
if($_POST['submit'])
{
if($_SESSION['SESS_ORDERNUM'])
{
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", "
. $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
if($_SESSION['SESS_LOGGEDIN'])
{
$sql = "INSERT INTO orders(customer_id, registered, date) VALUES("
. $_SESSION['SESS_USERID'] . ", 1, NOW())";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM']
. ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
$sql = "INSERT INTO orders(registered, date, session) VALUES("
. "0, NOW(), '" . session_id() . "')";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
}
}
$totalprice = $prodrow['price'] * $_POST['amountBox'] ;
$updsql = "UPDATE orders SET total = total + "
. $totalprice . " WHERE id = "
. $_SESSION['SESS_ORDERNUM'] . ";";
mysqli_query($updres);
header("Location: " . $config_basedir . "showcart.php");
} else {
require("header.php");
echo "<form action='addtobasket.php?id="
. $_GET['id'] . "' method='POST'>";
echo "<table cellpadding='10'>";
echo "<tr>";
if(empty($prodrow['image']))
{
echo "<td><img src='./productimages/dummy.jpg' width='50' alt='"
. $prodrow['name'] . "'></td>";
} else {
echo "<td><img src='./productimages/" . $prodrow['image']
. "' width='50' alt='" . $prodrow['name']
. "'></td>";
}
echo "<td>" . $prodrow['name'] . "</td>";
echo "<td>Select Quantity <select name='amountBox'>";
for($i=1;$i<=100;$i++)
{
echo "<option>" . $i . "</option>";
}
echo "</select></td>";
echo "<td><strong>£"
. sprintf('%.2f', $prodrow['price'])
. "</strong></td>";
echo "<td><input type='submit' name='submit' value='Add to basket'></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
}
require("footer.php");
error_reporting(E_ALL);
?>
there are two redirects that makes your user return to your home page
first:
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
make sure $_GET['id] has valid value
second:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$numrows = mysqli_num_rows($prodres);
// ...
if($numrows == 0)
{
header("Location: " . $config_basedir);
}
check your query in this line:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
make sure it returns not an empty results ( $numrows == 0 )
Test it first on your DBMS front-end
Being a complete noob, I'm trying to create a way for my php page to show all data registered in a database when the values of the columns "identity" and "idricovero" are the same ones used at the start of the session.
Currently it shows only the latest data entered, while I'd like the page to "update" with every new data.
Here's the code
<html>
<body>
<?php
require "connessione.php";
$operatore="";
session_start();
if (!empty($_SESSION['username'])) {$operatore = $_SESSION['username'];}
$idpazok = $idricok = $cartellaok = 0;
$identity = $idpaz = "";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
if (!empty($_GET['identity'])) {
$identity = test_input($_GET['identity']);
$idpazok = 1;
}
if (!empty($_GET['idricovero'])) {
$idricovero = test_input($_GET['idricovero']);
$idricok = 1;
}
}
if ($idricok AND $idpazok) {
//prendo i dati della cartella paziente
$query = "SELECT * FROM Accertamentomirato WHERE `identity` = '".$identity."' AND idricovero = '".$idricovero."'";
//echo "<h2>".$query."</h2>";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) > 0) {
$row = mysqli_fetch_assoc($results);
$dataorarilevazione = $row['dataorarilevazione'];
$csm1 = $row['csm1'];
$csm2 = $row['csm2'];
$csm3 = $row['csm3'];
$cartellaok=1;
} else {
echo "<h2 class=error> Cartella paziente non esistente</h2>"; //.mysqli_error($conn);
}
mysqli_free_result($results);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($cartellaok) {
echo "<h1>" . "ACCERTAMENTO MIRATO" . "</h1>";
echo "<fieldset>";
echo "<legend>".$datarilevazione. "</legend>";
echo "<fieldset>";
echo "<legend>".$orarilevazione."</legend>";
echo "<table>";
if (!empty($csm1)) {echo "<tr> " . "<td> " . "TEMPO DI REMPIMENTO CAPILLARE: " . "</td> " . "<td>".$csm1."</td> " . "</tr>";}
if (!empty($csm2)) {echo "<tr> " . "<td> " . "SENSIBILITÀ TATTILE: " . " </td> " . "<td>".$csm2."</td> " . "</tr>";}
if (!empty($csm3)) {echo "<tr> " . "<td> " . "MOBILITÀ DELLE ESTREMITÀ: " . "</td> " . "<td>".$csm3."</td> " . "</tr>";}
echo "<tr> " . "<td> " . "Operatore: " . "</td> " . "<td>".$operatore." </td> " . "</tr>";
echo "</table>";
echo "</fieldset>";
echo "</fieldset>";
}
?>
</body>
</html>
The code is of a short-answer quiz for a uni course. What I'd like to do is to match students' response to answer stored in database. A matching answer (or keywords) counts as a point. I'm having trouble counting the total points. The preg_match() results are already correct. Here is the code:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL ^ E_NOTICE);
include("dbconn.php");
session_start();
if(isset($_POST['Submit']))
{
$id = $_SESSION['tf1_sid'];
$qno = $_POST['q_no'];
?>
<head></head>
<body>
<form id="form1" name="form1" method="post" action="">
<table width="590" border="1" cellpadding="2" align="center">
<?php
//db query to obtain i_id - to insert to RESULT table
$sql_i = "SELECT i_id FROM ins_stud WHERE s_id = '$id'";
$query_i = mysql_query($sql_i) or die("MySQL Error: " . mysql_error());
$data_i = mysql_fetch_assoc($query_i);
$ins_id = $data_i['i_id'];
//echo $ins_id;
//$correct = 0;
$total = 0;
$arr_ind = 1;
$atext = array(1);
$ans = array(1);
for($i=1;$i<=$qno;$i++){
$repStr = str_replace("1", $i, "answer_1");
//echo "Question ". $i .": ". $repStr;
$ans[] = $_POST[$repStr];
//echo $ans;
$sql_check = "SELECT q_ans FROM question WHERE q_id='$i'";
$query_ch = mysql_query($sql_check) or die("MySQL Error: " . mysql_error());
$data_ch = mysql_fetch_assoc($query_ch);
$atext[] = $data_ch['q_ans'];
// insert answer to table
//$sql_eval = "INSERT INTO eval_set (s_id, q_id, response, response_value, created) VALUES ('" . $id . "', '" . $i . "', '" . $ans . "', '" . $correct . "', CURDATE())";
//mysql_query($sql_eval) or die ("Error: " . mysql_error());
}
// insert result to table
//$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES ('" . $total . "','" . $id . "','" . $ins_id . "')";
//mysql_query($sql_result) or die ("Error: " . mysql_error());
// db query for questions
$sql_q = "SELECT q_id, q_no, q_text, q_ans, q_help FROM question";
$query_q = mysql_query($sql_q) or die("MySQL Error: " . mysql_error());
// start loop for questions & answers
$rad = 1;
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
echo "<tr><td width='20' align='center' valign='top'><label><br><input name='q_no' size='1' type='hidden' value=". $data_q['q_no'] .">". $data_q['q_no'] ."</label></td>";
echo "<td><p align='justify'>". $data_q['q_text'] ."<br />";
if(preg_match_all("/". $ans[$arr_ind]. "/i", " . $atext[$arr_ind] . ")){
echo "Something matches";
$total = total + 1;
}
//else if (preg_match("/^$/", " . $atext[$arr_ind] . "))
//echo "Empty string";
else
echo "Wrong";
echo "<p align='justify'><b>YOUR ANSWER: </b>". $ans[$arr_ind]. "</p>";
echo "<p align='justify'><label><b>SUGGESTED ANSWER:</b> <br><input name='answer_".$rad."' type='hidden' value=''>". $atext[$arr_ind] . "</label></p>";
$rad++;
$arr_ind++;
}
mysql_free_result($query_q);
include("dbconn.php");
echo "</table>";
echo "<h2>" . $total . " questions correct. - Answer Review</h2>";
echo "</form>";
?>
</body>
</html>
<?php
}
else
{
header("Location:s_login.php");
}
// close db connection
mysql_close($dbconn);
?>
You are missing a $ in:
$total = total + 1;
Or just use:
$total++;
I have developed a search function which finds patients by their forename and surname and displays the results. However, after implementing the PHP code, the search results are not displaying.
Please note: The error messages are not displaying either;
Does anyone have any idea's why it is not displaying the search results?
<html>
<h1>Search By Name</h1>
<form action="" method="get">
<label>Name:
<input type="text" name="keyname" />
</label>
<input type="submit" value="submit" />
</form>
</body>
</html>
<?php
//capture search term and remove spaces at its both ends if there is any
if(isset($_GET['submit'])){
if(!isset($_GET['keyname'])){
$_GET['keyname'] = "";
$keyname = $_GET['keyname'];
$searchTerm = trim($keyname);
//check whether the name parsed is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
//database connection info
$host = "localhost"; //server
$db = "a&e"; //database name
$user = "root"; //dabases user name
$pwd = ""; //password
//connecting to server and creating link to database
$link = mysqli_connect($host, $user, $pwd, $db);
//MYSQL search statement
$query = "SELECT PatientID, Forename, Surname, Gender, Patient_History, Illness, Priority FROM patient WHERE 'Forename' = '$keyname' OR 'Surname' = '$keyname'";
$results = mysqli_query($link, $query);
/* check whethere there were matching records in the table
by counting the number of results returned */
if(mysqli_num_rows($results) >= 1)
{
$output = "";
while($row = mysqli_fetch_array($results))
{
$output .= "PatientID: " . $row['PatientID'] . "<br />";
$output .= "Forename: " . $row['Forename'] . "<br />";
$output .= "Surname: " . $row['Surname'] . "<br />";
$output .= "Gender: " . $row['Gender'] . "<br />";
$output .= "Illness: " . $row['Illness'] . "<br />";
$output .= "Priority: " . $row['Priority'] . "<br />";
$output .= "Patient History: " . $row['Patient_History'] . "<br /><br />";
}
echo $output;
}
else {
echo "There was no matching record for the name " . $searchTerm; }
}
}
?>
Tried to post this on your previous question. If you want people to answer these you'll have to leave them up long enough for people to answer.
<?php
$form = "<html>
<h1>Search By Name</h1>
<form method=\"get\">
<label>Name:
<input type=\"text\" name=\"keyname\" />
</label>
<input type=\"submit\" value=\"Search\" />
</form>
</body>
</html>";
//capture search term and remove spaces at its both ends if there is any
if(!empty($_GET['keyname'])){
$keyname = $_GET['keyname'];
$searchTerm = trim($keyname);
//database connection info
$host = "localhost"; //server
$db = "a&e"; //database name
$user = "root"; //dabases user name
$pwd = ""; //password
//connecting to server and creating link to database
$link = mysqli_connect($host, $user, $pwd, $db);
//MYSQL search statement
$query = "SELECT PatientID, Forename, Surname, Gender, Patient_History, Illness, Priority FROM patient WHERE Forename LIKE '%$searchTerm%' OR Surname LIKE '%$searchTerm%'";
$results = mysqli_query($link, $query);
/* check whethere there were matching records in the table
by counting the number of results returned */
if(mysqli_num_rows($results) >= 1){
$output = "";
while($row = mysqli_fetch_array($results))
{
$output .= "PatientID: " . $row['PatientID'] . "<br />";
$output .= "Forename: " . $row['Forename'] . "<br />";
$output .= "Surname: " . $row['Surname'] . "<br />";
$output .= "Gender: " . $row['Gender'] . "<br />";
$output .= "Illness: " . $row['Illness'] . "<br />";
$output .= "Priority: " . $row['Priority'] . "<br />";
$output .= "Patient History: " . $row['Patient_History'] . "<br /><br />";
}
}else{
$output = "There was no matching record for the name " . strip_tags($searchTerm);
}
} else {
$output = "Enter name you are searching for.";
}
echo "$form\n$output";
?>
You should put your search code into a block that gets run only if the search term has a value:
if( empty($searchTerm) )
{
echo "Enter name you are searching for.";
}
else
{
// run your search code here and display the result.
}
How do I align and put div tags around the displayed data? I am very new to php and hope you guys can help!
Thanks!
James
<?php
$conn = mysql_connect("", "", "");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '$search%' AND lastname LIKE '$searchterm'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["name"];
echo $row["lastname"];
echo $row["email"];
}
mysql_free_result($result);
?>
<?php echo $row["name"];?>
<br>
<?php echo $row["lastname"];?>
<br>
<?php echo $row["email"];?>
I think you mean something like this:
while ($row = mysql_fetch_assoc($result)) {
echo '<div class="data">';
echo '<label>' . $row["name"] . '</label>';
echo '<label>' . $row["lastname"] . '</label>';
echo '<label>' . $row["email"] . '</label>';
echo '</div>';
}
Anyway I don't understand the need to have this:
<?php echo $row["name"];?>
<br>
<?php echo $row["lastname"];?>
<br>
<?php echo $row["email"];?>
which will never echo nothing (will always echo the empty string) because when the script reaches this code, $row = false.