Fetch data from mysql to textarea, but if not exist print null - php

I made some little translator.
And if word exist in database all is ok. But if word didnt exist in database, word isnt printed. I add some code to print if result is empty but didnt work.
Any idea why word that not exist in database isnt printed?
Here is code:
<p><form method="post" action="prevedi.php">
<textarea id="prevedi" name="prevedi" style="margin: 2px; height: 137px; width: 380px;">
<?php
echo htmlentities($_POST['prevedi']);
?>
</textarea>
<textarea id="prevod" disabled="disabled" name="prevod" style="margin: 2px; height: 137px; width: 380px; border: 0px;" readonly>
<?
if (isset($_POST['prevedi'])) {
//Kreci
$prevedi = htmlentities($_POST['prevedi']);
$prevedi = explode(" ",$prevedi);
foreach ($prevedi as $word) {
$slovo = $word[0];
$result = mysqli_query($con,"SELECT * FROM $slovo WHERE srpski='$word'");
if (!empty($result)) {
while($row = mysqli_fetch_array($result))
{
$prevod .= $row['romski']." ";
}
}
else
{
$prevod .= "".$word." ";
}
}
echo $prevod;
//Kraj isset
}
?>
</textarea><br>
<input name="translate" type="submit" value="Translate"/>
</form>
</p>

Because your result is not empty. You should check if $result number of rows is > 0
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result)){
$prevod .= $row['romski']." ";
}
}else{
$prevod .= $word." ";
}

i think you have to initialize $prevod before assigning it the way you did.
$prevod = "";
if (!empty($result)) {
while($row = mysqli_fetch_array($result))
{
$prevod .= $row['romski']." ";
}`enter code here`
}
else
{
$prevod .= "".$word." ";
}
}
echo $prevod;

Related

Username Keeps being Validated as a Name

//This is my php for the registration: <?php
/* Program name: checkBlankOnly_2.php
* Description: Program displays the blank form and checks
* all the form fields for blank fields.
*/
if(isset($_POST['submitted']) and $_POST['submitted'] == "yes")
{
foreach($_POST as $field => $value)
{
if(empty($value))
{
if($field != "firstname")
{
$blank_array[] = $field;
}
}
else
{
$good_data[$field] = strip_tags(trim($value));
}
}
if($blank_array > 0)
{
$message = "<p style='color: red; margin-bottom: 0;
font-weight: bold'>
You didn't fill in one or more required fields.
You must enter:
<ul style='color: red; margin-top: 0;
list-style: none' >";
/* display list of missing information */
foreach($blank_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($good_data);
include("logic.inc");
exit();
}
foreach($_POST as $field => $value)
{
if(!empty($value))
{
$name_patt2 = "/^[a-z]\w{2,23}[^_]$/i";
$name_patt = "/^[A-Za-z' -]{1,50}$/";
$pass_patt = "/^[a-zA-Z][0-9a-zA-Z_!$##^&]{5,20}$/";
$phone_patt = "/^[0-9)(xX -]{7,20}$/";
$addr_patt = "/^[A-Za-z0-9 .,'-]{1,50}$/";
$zip_patt = "/^[0-9]{5}(\-[0-9]{4})?$/";
$postal_patt = "/^[A-Za-z0-9]{6}$/";
$email_patt = "/^.+#.+\\..+$/";
$radio_patt = "/Canada|USA/";
if(preg_match("/uname/i",$field))
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
if(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
if(preg_match("/phone/i",$field))
{
if(!preg_match($phone_patt,$value))
{
$error_array[] = "$value is not a valid phone number";
}
} // endif phone format check
if(preg_match("/country/i",$field))
{
if(!preg_match($radio_patt,$value))
{
$error_array[] = "$value is not a valid status";
}
}
}
$clean_data[$field] = strip_tags(trim($value));
}
if($error_array > 0)
{
$message = "<ul style='color: red; list-style: none' >";
foreach($error_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($clean_data);
include("logic.inc");
exit();
}
else
{
$cxn = mysqli_connect($host,$user,$passwd,$dbname)
or die("Couldn't Connect to Server");
foreach($clean_data as $field => $value)
{
$clean_data[$field] = mysqli_real_escape_string($cxn,$value);
}
$sql = "INSERT INTO users (uname,password,lastname,firstname,city,address,state_province,country,phone,email,date) VALUES ('$clean_data[uname]','$clean_data[password]','$clean_data[lastname]','$clean_data[firstname]','$clean_data[city]','$clean_data[address]','$clean_data[state_province]','$clean_data[country]','$clean_data[phone]','$clean_data[email]','$clean_data[date]')";
$result = mysqli_query($cxn,$sql)
or die("Couldn't Execute Query");
include("stored.inc");
}
}
else
{
include("logic.inc");
}
?>
\\ This is my HTML code:
<!doctype html>
<?php
ini_set("display_errors","on");
error_reporting(E_ALL | E_STRICT);
ini_set("include_path","./includes");
include("dbinfo.inc");
?>
<?php
/* Program Name: logic.inc
* Created by: Clayton Korth
* Created On: 2022-05-20
* Description: Defines a form that collects a user's information */
$labels = array ("uname" => "Username","firstname" => "First Name","lastname" => "Last Name","address" => "Address","city" => "City","zip_postal" => "Zip Code","phone" => "Phone","email" => "Email");
$country = array("Canada","US");
$submit = "Submit Information";
$empty_array = array();
$blank_array = array();
?>
<?php
$cxn = mysqli_connect($host,$user,$passwd,$dbname)
or die ("Couldn't Connect to Server");
$query = "SELECT DISTINCT name FROM states ORDER BY `id` ASC";
$result = mysqli_query($cxn,$query) or die ("Couldn't Execute Query.")
?>
<html>
<head>
<style type='text/css'>
<!--
form {
margin: 1.5em 0 0 0;
padding: 0;
align-content: center;
}
.field {padding-bottom: 1em;}
h1 {text-align: center;}
label {
font-weight: bold;
float: left;
width: 20%;
margin-right: 1em;
text-align: right;
}
#submit {margin-left: 35%}
--></style>
<meta charset="utf-8">
<title>Form Script</title>
</head>
<body>
<?php
/* loop that displays the form */
echo "<div class='row'><div class='col-lg-6>'";
echo "<h3>Sign Up Form</h3>";
echo "<form id='sForm' form action='checkBlankOnly2.php' method='post'>";
foreach ( $labels as $field => $label)
{
echo "<div class='field'>
<label for='$field' style='font-weight: bold;'>$label</label>
<input id='$field' name='$field' type='text' placeholder='$label'
size='42' /></div>";
if($field == "uname")
{
echo "<div class='field'><label for='password'>Password</label><input id='password' placeholder='Password' name='password' type='password' size='42'></div>";
}
if($field == "city")
{
echo "<form action='checkBlankOnly2.php' method='POST' style='margin-left: 3em'>
<label for'name' style='font-weight: bold'>State/Province:</label>
<select id='name' name='name' style='margin-top: 3em'>";
while($row = mysqli_fetch_assoc($result))
{
extract($row);
echo "<option value='$name'>$name</option>";
}
echo "</select>";
echo "<div class='field'><label for='country'>Country</label><input type='radio' name='country' checked='checked' value='Canada' >$country[0]
<input type='radio' name='country' value='US' style='margin-left: 1.5em'>$country[1]</div>";
}
}
echo "<div class='field'><input type='hidden' name='submitted' value='yes'</div>";
echo "<div id='submit'><input type='submit' value='$submit'></div>";
echo "</div></div>"
?>
</body>
</html>
Above is my code for my registration.php as I am tasked to create an Login Application. What happens is that when I submit the form it validates everything except the username causing it to be validated by using name instead of username. I am wondering if I had done something wrong with my code. I am fairly new to PHP and Dynamic Web Design
You'll probably want to read up on regular expressions, which is what preg_match() uses.
https://www.php.net/manual/en/function.preg-match.php
The following code will first get a positive match of uname against /uname/i, and then compare the value against $name_patt2, but then it will also get a positive match of uname against /name/i, because the pattern isn't anchored to the beginning with ^.
if(preg_match("/uname/i",$field))
{
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
}
if(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
You can go one of 3 ways, if you're leaving the rest of the program alone:
One is to replace the $field checks with anchored regexes, like this:
if(preg_match("/^uname/i", $field))
...
A second option is to elseif so you won't check the other patterns for $field if the first one already matched:
if(preg_match("/uname/i",$field))
{
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
}
elseif(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
The third option (depending on what the field naming actually looks like), would be to use exact string matches instead of regex matches:
if($field == "uname")
{
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
}
if($field == "name")
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}

I am getting only one row from database php

I have this following PHP code in search.php to gather information from the form in the same file. It's a search engine and when I put something into the search bar I get only one row even when I should get more than one row.
Here is php script:
<?php
$error = "";
$con=mysqli_connect('localhost', 'root', '');
$db=mysqli_select_db($con, 'vodici');
if(isset($_POST['button'])){ //trigger button click
$search=$_POST['search'];
$query=mysqli_query($con,"select distinct * from users where meno like '%{$search}%' || priezvisko like '%{$search}%' || mesto like '%{$search}%' || kraj like '%{$search}%' || rok_narodenia like '%{$search}%' || email like '%{$search}%' ");
if (mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_array($query)) {
$div = "<div style='border: 1px solid black; border-radius: 5px;'>".$row['id'];
$vysledok = "<h2 style='text-decoration: underline; padding-left: 2%;'>".$row['meno']." ".$row['priezvisko']."</h2>";
$mail = "<p style='padding-left : 2%; font-size: 11px;'><strong>Rok narodenia:</strong> ".$row['rok_narodenia']." <br><strong>E-mail: </strong> ".$row['email']."</p>";
$mesto = "<p style='padding-left: 2%'><strong>Mesto:</strong> ".$row['mesto']." <strong>Kraj:</strong> ".$row['kraj']."</p>";
$div_end = "</div>";
}
}else{
$error = "Nič sme nenašli :/ <br><br>";
}
}
mysqli_close($con);
?>
Here is form:
<form class="search-form" action="" method="post">
<div class="input-group">
<input name="search" type="text" class="form-control" placeholder="Vyhľadať...">
<div class="input-group-append">
<button class="btn btn-secondary" type="submit" name="button"><i class="fa fa-search"></button></i>
</div>
</div>
</form>
<p><?php if(isset($_POST['button']) && $error == "") {
while($row = mysqli_fetch_array($query)) {
echo $div,$vysledok,$mail,$mesto,$div_end;
}
}?></p>
<p><?php if(isset($_POST['button']) && $error !== "") {echo $error;}?></p>
What can I do here? I am out of ideas
Thanks
You only added one row. You need to add each row to the generated html.
$result = '';
if (mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_array($query)) {
$div = "<div style='border: 1px solid black; border-radius: 5px;'>".$row['id'];
$vysledok = "<h2 style='text-decoration: underline; padding-left: 2%;'>".$row['meno']." ".$row['priezvisko']."</h2>";
$mail = "<p style='padding-left : 2%; font-size: 11px;'><strong>Rok narodenia:</strong> ".$row['rok_narodenia']." <br><strong>E-mail: </strong> ".$row['email']."</p>";
$mesto = "<p style='padding-left: 2%'><strong>Mesto:</strong> ".$row['mesto']." <strong>Kraj:</strong> ".$row['kraj']."</p>";
$div_end = "</div>";
$result .= $div. $vysledok. $mail.$mesto. $div_end ;
}
}else{
$error = "Nič sme nenašli :/ <br><br>";
}
echo $result;
}
In compensation to wakeels answer, that is correct, I would like to ask you to use prepared statements like in my example below
$sql="
SELECT `id`,`meno`,`priezvisko`,`rok_narodenia`,`email`,`mesto`,`kraj`
FROM `users`
WHERE
`meno` LIKE '%?%'
OR `priezvisko` LIKE '%?%'
OR `mesto` LIKE '%?%'
OR `kraj` LIKE '%?%'
OR `rok_narodenia` LIKE '%?%'
OR `email` LIKE '%?%'
;"
$stmt = $con->prepare($sql);
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $div,$vysledok,$mail,$mesto,$div_end;
}

How do I separate the while loop search results from the footer position?

The logical error here is that the footer's margin position is affected by the while loop results.
Here's the logical view of the problem: https://www.dropbox.com/s/oxyt5o4pzmarome/before%20and%20after.png?dl=0
here's my code:
<div id="print_output1">
<?php
$con=mysql_connect("localhost","root","");
mysql_set_charset("UTF8", $con);
if(!$con)
{
die("Could not connect." .mysql_error());
}
mysql_select_db("dictionary_enhanced", $con);
if (isset($_POST['word']))
{
$search = $_POST['word'];
$search1=addslashes($search);
$query = "SELECT *" .
" FROM maranao, maranao_meaning, english, filipino, translate".
" WHERE maranao.mar_id = maranao_meaning.mar_id and maranao.mar_id = translate.mar_id and filipino.fil_id = translate.fil_id and english.eng_id = translate.eng_id and maranao.maranao_word like '$search1%' ORDER BY maranao.maranao_word ASC";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows==0)
{
echo "No Results Found. Please try again";
}
$previous_word = "";
$row = 0;
while($row = mysql_fetch_array($result))
{
// AM - Show the word only if it's a new one
if ($row["maranao_word"] != $previous_word)
{
echo "<div style='margin-bottom: 3px; color: white;'>.</div>";
// AM - close the previous word definition
if ($row == 0)
{
}
?>
<div style = "font-family:'Times New Roman'; font-size: 17px;">
Maranao word: <b><i><?php echo $row['maranao_word']; ?></i></b><br>
English word: <b><?php echo $row['english_word']; ?></b><br>
Filipino word: <b><?php echo $row['filipino_word']; ?></b><br>
Definition:
<?php
}
?>
<font color="white">:</font>
<div style="width:600px; border:0px solid orange; margin-left: 100px; word-wrap:break-word; margin-top: -17px;"><b><ul><li><?php echo $row['definition'] ?></li></ul></b></div>
<?php
// AM - Update the previous word and the row count
$previous_word = $row["maranao_word"];
$row++;
//echo "<br>";
}
// AM - close the last word definition
if ($row > 0)
{ echo "</div><br>"; }
}
mysql_close($con);
?>
</div><!-----end id="print_output1" ------>
</div><!-----end of id="container" ------>
</div><!-------end border shadow------->
<div id="footer"> <!---footer------>
footer <!---the footer here is affected when displaying all the results from the while loop above--->
</div>
</div> <!---------id="wrap"---->
You have not closed the div inside the while loop. Try with below code
<div id="print_output1">
<?php
$con = mysql_connect("localhost", "root", "");
mysql_set_charset("UTF8", $con);
if (!$con) {
die("Could not connect." . mysql_error());
}
mysql_select_db("dictionary_enhanced", $con);
if (isset($_POST['word'])) {
$search = $_POST['word'];
$search1 = addslashes($search);
$query = "SELECT *" .
" FROM maranao, maranao_meaning, english, filipino, translate" .
" WHERE maranao.mar_id = maranao_meaning.mar_id and maranao.mar_id = translate.mar_id and filipino.fil_id = translate.fil_id and english.eng_id = translate.eng_id and maranao.maranao_word like '$search1%' ORDER BY maranao.maranao_word ASC";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if ($num_rows == 0) {
echo "No Results Found. Please try again";
}
$previous_word = "";
$row = 0;
while ($row = mysql_fetch_array($result)) {
// AM - Show the word only if it's a new one
if ($row["maranao_word"] != $previous_word) {
echo "<div style='margin-bottom: 3px; color: white;'>.</div>";
// AM - close the previous word definition
if ($row == 0) {
}
?>
<div style = "font-family:'Times New Roman'; font-size: 17px;">
Maranao word: <b><i><?php echo $row['maranao_word']; ?></i></b><br>
English word: <b><?php echo $row['english_word']; ?></b><br>
Filipino word: <b><?php echo $row['filipino_word']; ?></b><br>
Definition:
<?php
}
?>
<font color="white">:</font>
<div style="width:600px; border:0px solid orange; margin-left: 100px; word-wrap:break-word; margin-top: -17px;"><b><ul><li><?php echo $row['definition'] ?></li></ul></b></div>
<?php
// AM - Update the previous word and the row count
$previous_word = $row["maranao_word"];
$row++;
echo "</div>";
//echo "<br>";
}
// AM - close the last word definition
if ($row > 0) {
echo "</div><br>";
}
}
mysql_close($con);
?>
</div><!-----end id="print_output1" ------>
footer

PHP Value of Variable is undefined

I am getting " Notice: Undefined index:k" in the PHP code. K is the name of the text field and I am using $_GET[] method to get the value of k. In the below mentioned example I am trying to keep the value available even after the form is submitted. This Code runs fine for the first time but the second time it gives the above error.
<form name="keywordquery" method="get" action="keywordsearch.php">
<fieldset class="fieldsetclass"><legend class="legendclass">Search by
Keywords</legend>
<div id="searchbox">
<input type="text" name="k" value="<?php if(isset($_GET['k'])){echo
htmlentities($_GET['k']);} ?>" style="border: 1px, thin; width:92%; "/> <input
type="image" style="margin-bottom: 0; margin-top: 2px;" src="search.png"
value="submit" />
</div>
</fieldset>
</form>
</div>
<table id="dataTable" cellpadding="0" cellspacing="0" border="1" style="border-
radius:20px; box-shadow: 9px 5px 8px #7E9044;">
<tbody>
<?php
// PAGINATION Code. check if the starting row variable was passed in the
URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
$k1 = $_GET['k'];
$term = explode(" ", $k1);
$query = "SELECT * FROM data ";
foreach ($term as $each) {
$i++;
if($i==1)
{
$query .= "WHERE keywords LIKE '%$each%' ";
}
else {
$query .= " OR WHERE keywords LIKE '%$each%' ";
}
}
$query .= "LIMIT $startrow, 1";
$connection = mysql_connect("xxxx", "xxxxx","");
if(!$connection)
echo "No database connected";
$dbase = mysql_select_db("xxxxxxxx", $connection);
if(!$dbase)
echo "No datatable connected";
$ourquery1 = mysql_query ($query);
if(!$ourquery1)
echo "No query found";
$row1 = mysql_num_rows ($ourquery1);
if ($row1 > 0)
{
while($result = mysql_fetch_assoc($ourquery1))
{
echo "<tr>";
$title = $result['title'];
$link = $result['link'];
$region = $result['region'];
$sector = $result['sector'];
$theme = $result['theme'];
echo "<td> <a href=$link><h3>$title<h3></a>";
echo "<h4>Sector: $sector
Theme: $theme
<br> Region: $region </td>";
}
}
echo "</tbody>";
echo 'Next';
echo 'Prev';
Replace the line:
$k1 = $_GET['k'];
with something like:
$k1 = isset($_GET['k'])? $_GET['k'] : $default_k_value;
You don't show the complete form so it is tough to tell what is wrong but here is a hint. Swap $_GET with $_REQUEST.
Example:
<?php if(isset($_REQUEST['k'])){echo
htmlentities($_REQUEST['k']);} ?>
If the form is using a POST method, the value would be in $_POST. If the form uses a GET method, the value would be in $_GET. However $_REQUEST will contain the form fields whether the form used POST or GET.

Making a PHP/MySQL Search Engine

In a site I'm making, I need a search engine to find songs for people to listen to. I have it working to the point that it can get info from the database and display them on the page. The problem comes when there are two songs with the same name. I have a system so the results will go to separate links, but when I search them they display the same image even though there is two separate sources for them. It also will make extra results for some reason. Here's my code:
<?php
if (isset($_GET['q'])) {
$q = $_GET['q'];
mysql_connect('********', '********', '********');
mysql_select_db('********');
$query = mysql_query("SELECT * FROM ******** WHERE title LIKE '$q'");
$numrows = mysql_num_rows($query);
} else {
echo "
<span style='font-family: Helvetica, Arial;font-weight: bold;font-size: 25px;'>Search</span>
<form action='http://www.example.com/search' method='get'>
<input placeholder='Search for music' type='text' name='q' style='font-weight:bold;padding:5px;width:300px;border-top-left-radius: 4px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 4px;border: 3px solid gray;background-color:#000000;color:#FFFFFF;' />
</form>
";
}
if ($numrows != 0) {
$index = 0;
$results = array();
while($row = mysql_fetch_assoc($query)) {
$results[$index] = $row;
$index++;
foreach ($results as $result) {
$url = "http://www.example.com?id=" . $row['id'];
$title = $row['title'];
$arturl = $row['art_url'];
if ($_GET['q'] != "") {
echo "
<a href='$url'>
<table>
<tr style='text-align:left;'>
<td><img src='$arturl' style='width:100px;height:100px;'></td>
<td>
<span class='songTitle'>$title</span>
<br/>
<span class='songArtist'>By: Unknown</span>
</td>
</tr>
</table>
</a>
<br />
";
}
}
}
} else {
if ($_GET['q'] != "") {
echo "
<span style='font-family: Helvetica, Arial;font-weight: bold;font-size: 25px;'>Search</span>
<form action='********' method='get'>
<input placeholder='Search for music' type='text' name='q' style='font-weight:bold;padding:5px;width:300px;border-top-left-radius: 4px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 4px;border: 3px solid gray;background-color:#000000;color:#FFFFFF;' />
</form>
";
echo "<br />No results where found.";
}
}
?>
while($row = mysql_fetch_array($result))Try $result['title'] instead of $row['title'];. Same goes to $url and $arturl
This should work.
if ($numrows != 0) {
$index = 0;
$results = array();
while($row = mysql_fetch_array($query)) {
$url = "http://www.example.com?id=" . $row['id'];
$title = $row['title'];
$arturl = $row['art_url'];
if ($_GET['q'] != "") {
echo "
<a href='$url'>
<table>
<tr style='text-align:left;'>
<td><img src='$arturl' style='width:100px;height:100px;'></td>
<td>
<span class='songTitle'>$title</span>
<br/>
<span class='songArtist'>By: Unknown</span>
</td>
</tr>
</table>
</a>
<br />
";
}
}
}
your codes seem right. However, to clarify, try to echo $arturl and see if it is getting the right source name. And also check the value in the database. Last thing is try to check whether the source image is in the correct folder. Try and give the feedback.

Categories