Thanks in advance to those who will have taken time to look at my issue. I fetch results from a table that describe activities of a contractor. There are a large number of True/False fields and I seek only to display those that are true. I create a field_name => field_type array and parse my display accordingly. (apologies for the large code snippet.)
$result = $mysqli->query($visitsSQL);
if ( $result->num_rows == 0 ){ // Visit records don't exist
$_SESSION['message'] = "Cannot find any unpaid visits";
header("location: error.php");
}
else { // unpaid visits exist
$fields= array();
while ($finfo = mysqli_fetch_field($result)){
$fields [$finfo->name]= $finfo->type ; //this array holds field names -> field types
} //finish fetching keys and types
echo "<br>";
echo "<br>Begin visit records<br>";
echo "<div class='review_row'> </div>"; //this puts a thin line to separate visits
while ($visit = $result->fetch_assoc()) { //here's where each visit is compiled and sent to screen
echo "<div class='review_row'>"; //this puts a thin line on the bottom to separate visits
foreach ($fields as $k => $v) {
$field_name = $k;
$field_type = $v;
$field_data = $visit[$field_name];
switch ($field_type) {
case 1: //The field is a True / False field
if ($field_data ==1){ //show the field only if the value is set to True
echo "I am a YES/NO field called " . $field_name . " <br>"; //This line is a test
echo "<span style='color: #009999;> - " . $field_name . "</span><br>";
}
break;
case 4: //The field is a double numeric
if ($field_data != null) { //show the field only if the value is set to True
echo "<span style='color: #b38f00';>" . $field_name . "</span> " . $field_data . "<br>";
}
break;
case 253: //A text field
if ($field_data != null) {
echo "<span style='color: #b38f00';>" . $field_name . "</span> " . $field_data . "<br>";
}
break;
case 254: //a Datetime field
if ($field_data != null) {
echo "<span style='color: #b38f00';>" . $field_name . "</span> " . $field_data . "<br>";
}
break;
default: { //field type is not represented above
// do nothing so far I take care of each field type above
}
} //end of switch
} //end of foreach
} //end of while loop for the query results
echo "</div>";
} // end of if / else that determine if there are records to display
The strange results occur in the "switch" statement where "case 1". My current test record has 7 YES/NO fields whose values are all set to 1. They are
Prepared evening meal
Cleaned up evening meal dishes
Shopped for groceries
Washed and folded clothes
Washed bedding
Vacuumed carpets
Swept kitchen floor
I should get two "echo"s for each "field_type = 1": (1) my test echo and (2) what I eventually want to display, but for some reason they display alternately - see image below. I've fought with this for two days, trying if/then parsing as well, but I come up with this "every-second-one" type of result.
screenshot of output from query
Thanks for any thoughts or direction.
I have found the problem & corrected it. It had to do with the "span..." tags. I replaced the inline "style=..." with a class. I set the the color within the class then removed settings with an "class: after" section.
Related
My url type is like "http://localhost/boardgame/profile/Duncan/" the last word is the user name...
I just try to get some data from database and I need a user name to do this. I tried to get it from page URL but it doesn't work. Where did I go wrong? What has to be done? I'll be greateful if anybody can help...
<?php
$actual_link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//echo $actual_link;
$rest = substr($actual_link, 35, -1);
echo $rest;
$link = mysqli_connect("localhost", "root", "", "bgt");
if (mysqli_connect_error()) {
die ("Veritabanı bağlantısında hata var");
} if (($rest) !="") {
if (get_current_user_id($link) == '0') {
echo "<p>Kullanıcının koleksiyonunu görebilmek için giriş yapmanız
gerekiyor.</p>";
} else {
$query = "SELECT TITLE FROM wp_user_collections WHERE `user_name` =
'".mysqli_real_escape_string($link, $rest)."'";
echo "<div><h1>'".mysqli_real_escape_string($link, $rest)."'in
Koleksiyonu</h1><div>";
if($result = mysqli_query($link, $query)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>Oyun Adı</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>'" . $row['TITLE'] . "'</td>";
echo "</tr>";
}
echo "</table></div>";
}
}
}
} else {
echo "Kullanıcının koleksiyonunu görebilmek için <a
href='http://localhost/boardgame/profile/'".mysqli_real_escape_string($link,
$rest)."'>tıklayınız</a>";
}
?>
Here is the solution I have thought...using array then extracting the last element (or second last since there is a trailing '/' slash which is a delimiter)
$uri="http://localhost/boardgame/profile/Duncan/";
$uriParts=explode('/', $uri); //converts the uri string into an array of words separated by forward slash
$name=$uriParts[sizeOf($uriParts)-1-1]; //the user name comes from 2nd last item as the last item is empty
echo $name;
I could suggest you use Regular Expression to extract the user name, however I'm not well versed with it yet.
I'm using this code for my questionnaire, how can I prevent them from inserting their answers/post? If they did not yet clicked all the radio buttons, that is given within the system which is the questions? And how to add an error message besides the question?
if(isset($_POST['question']))
{
$AddQuery = "INSERT INTO tblevaluate (evaluateid,professorid,professorname,studentid,course,section,subjectid,subjectname) VALUES ('','$server_professorid','$server_name',' $username','$course','$section','$server_subjectid','$server_subject')";
mysql_query($AddQuery, $connect);
$id = mysql_insert_id();
foreach($_POST['question'] as $questionId => $answer)
{
$AddQuery = "INSERT INTO tblanswer (answervalue,evaluateid,professorid,professorname,studentid,course,section,subjectid,subjectname) VALUES ($answer,$id,$server_professorid,'$server_name',$username,'$course','$section',$server_subjectid,'$server_subject')";
mysql_query($AddQuery, $connect);
header('Location: evaluate.php');
}
}
while($row = mysql_fetch_array($result))
{
echo "<br>";
echo "<strong>" . $row["questionno"] . ".</strong> " . $row["question"] . "";
echo "<br>";
echo "<input type = radio name = 'question[". $row ["questionid"] . "]' value = '5'/><label>5</label>";
echo "<input type = radio name = 'question[". $row ["questionid"] . "]' value = '4'/><label>4</label>";
echo "<input type = radio name = 'question[". $row ["questionid"] . "]' value = '3'/><label>3</label>";
echo "<input type = radio name = 'question[". $row ["questionid"] . "]' value = '2'/><label>2</label>";
echo "<input type = radio name = 'question[". $row ["questionid"] . "]' value = '1'/><label>1</label>";
echo "<br>";
echo "<hr size = 5 color = black noshade >";
}
The Answer came from user2864740
Make the radio groups required is the simplest way to prevent form submission. To be 'truly safe' you'd also need to ensure that all the values are set to allowable values on the server, but meh - not really any point even talking about that when there is Blatant SQL Injection vulnerabilities. Also, your tables are poorly normalized. – user2864740
I'm stepping up from mysql to PDO and I'm getting close as all my fields print now except the images. These are held in a separate file with only the address in the database. I can retrieve these in mysql but I'm having trouble doing it in PDO.
Where I should see the image, the best I've been able to achieve is getting it to print "Arrayh" at the end of each line. I don't seem to be able to find how to do this anywhere so here I am again. This is the part of the file that prints.
$STM->bindParam(':Country', $Country, PDO::PARAM_STR);
$STM->execute();
$row= $STM->fetchAll();
$img_url = "http://www.xxxxx.net/images/";
if(count($row)){
foreach($row as $data){
echo $data['Country'] ." ".$data['Year']." ".$data['Description']." ".$data.$img_url['Images']."<br />";
}
}else {
echo 'no row found';
}
Say if you called your image field img_url
foreach($row as $data){
echo "<img src='"$data['img_url']."'><br />";
}
I've eventually got it to work so I will put what I've used here otherwise this question will be useless for people in the future who have the same problem. The echo data line is replaced by two lines :
echo $data['Key'] ." ".$data['Country'] ." ".$data['Year']." ".$data['Description']." ";
echo "<img src='$img_url".$data['Images']."' <br /><br />" ;
"<br />";
Now I just need to get it into a table to neaten it up a bit. Thanks to all who helped.
I'm trying to build a members-system in which you can view certain values from a database.
It worked, so that was great, but I'm having a problem now because I'm using a NULL value on 'age'.
When viewing a profile page, it looks like this:
$id = $_GET["id"];
$result = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember`=$_GET[id]");
$row = mysql_fetch_array($result);
echo "<b>" . $row['userusername'] . "</b>: </p>"; ?>
<?php
$id = $_GET["id"];
$result = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember`=$_GET[id]");
$noage = mysql_query("SELECT ISNULL([age]) FROM membersfromsite WHERE `idofmember`=$_GET[id]");
while ($row = mysql_fetch_array($result))
{
echo "<p class='middle'>id-number: " . $row['idofmember'] . "<br>";
echo "Username: " . $row['userusername'] . "<br>";
if ($noage)
{
echo "Age not specified";
}
else
{
echo "Age: " .$row['age'] ;
}
}
I have tried all kinds of other things, but the problem which I 'm having is that it either returns 'Age not specified' on every userpage or the age on every userpage, including the pages with a NULL value, which makes it look like:
Age:
The code which you can see above returns the age on every page, including the pages with an age which is set to NULL. What I don't understand is if I change the code to this:
$noage = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember`=$_GET[id] AND age IS NULL");
it simply doesn't work. Since I'm using IS NULL instead of = NULL I don't really see why this shouldn't work, but I guess it has to do with the IF which is inside the 'while' thing, I don't really see in what other way I could fix this though...
I'm having an idea what the problem is, because I think that there is already a MyQS, Query done with Results and $noage is maybe ignored because of this, but I don't know how to solve this.
You don't need to do a whole separate $noage query.
Just do:
if(!$row['age'])
{
echo "Age not specified";
}
else
{
echo "Age: " .$row['age'] ;
}
Instead of if($noage) use if(!$row['age']) and skip the second query.
The other reason your code does not work is that the second query returns an array with something like array('expr1' => 0) which is not false. You only get a false result if nothing is found.
The reason why = NULL does not work? There are books written about it, it is just as it is.
Rather than relying on MySQL to tell us if no age was found or not, we can programatically determine whether the age value is Null right in PHP.
Here is an example:
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember` = '" . mysql_real_escape_string($id) . "'");
while($row = mysql_fetch_array($result)) {
echo '<p class='middle'>id-number: ' . $row['idofmember'] . '<br>';
echo 'Username: ' . $row['userusername'] . '<br>';
if($row['age'] === Null) {
echo "Age not specified";
} else {
echo "Age: " .$row['age'] ;
}
}
Thank you for taking the time to read this. This question may or may not have been answered before, I might have been looking in the wrong place, but I've hit a dead end wall here and I hope I could ask for some help finding a solution.
I'm using a basic form with a validation for specific fields and checkboxes before I'm sending them in a query to my database.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// validate the text inputs
$err = array();
if (empty($_POST['A'])) {
array_push($err, "A is required.");
}
if (empty($_POST['B'])) {
array_push($err, "B is required.");
}
if (empty($_POST['C'])) {
array_push($err, "C is required.");
} else {
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
if (!eregi($pattern, $_POST['email'])) {
array_push($err, "Incorrect email.");
}
}
if (empty($_POST['D'])) {
array_push($err, "D is required.");
if (sizeof($err) != 0) {
echo "<p style='color: red'>The following files haven't been filled yet.</p>";
echo "<ul style='list-style:circle !important;color: red !important;'>";
foreach ($err as &$value) {
echo "<li style='background: 0;list-style: disc inside none;color: red;'>" . $value . "</li>";
}
echo "</ul>";
echo "<br/>";
}
// validate the agree checkbox
if (sizeof($err) == 0 && !isset($_POST['agree'])) {
array_push($err, "Please agree with the ToS.");
foreach ($err as &$value) {
echo "<p style='color: red'>" . $value . "</p>";
}
}
}
?>
Then the inside the form we got this:
<?php echo isset($_POST['a']) ? $_POST['a'] : ''; ?>"
The other lines are the same, so I'll save you from having to read a huge block. From there on I sent the code towards:
<?php
// redirect if form is valid
if (sizeof($err) == 0 && isset($_POST['agree'])) {
// set post data in session
session_start();
$_POST = $_SESSION['POSTDATA'];
$con = mysqli_connect("localhost", "x", "y", "z");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO esselte_nl (a, b, email, c, d) VALUES
('$_POST[a]',
'$_POST[b]',
'$_POST[email]',
'$_POST[c]',
'$_POST[d]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
// redirect to result.php
exit('<meta http-equiv="refresh" content="0; url=resullt"/>');
return;
session_destroy();
}
?>
Worst thing is, I'm fairly certain it's some very small error somewhere and I'm overlooking it, terribly frustrating. So if anyone could potentially point out whatever I'm doing wrong here, I'd appreciate it.
With friendly regards,
user2747008 (I really should pick a name though)
PS: Sorry about that, I messed up copying pasting the information.
$sql = "INSERT INTO esselte_nl (a, b, email, c, d) VALUES
('$_POST[a]',
'$_POST[b]',
'$_POST[c]',
'$_POST[email]')";
Your insert statement has 5 field names, but only 4 values, and they aren't in the correct order.