In the PHP file can anyone help me directly making a for loop where I don't know the number of rows that are going to be selected.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
$index = 0;
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$myarray[$index] = $row["firstname"];
$index++;
$myarray[$index] = $row["lastname"];
$index++;
$myarray[$index] = $row["email"];
$index++;
}
}
else
{
echo "0 results";
}
$conn->close();
?>
The Javascript code contains javascript of a search bar suggestion code and here i didn't mention the typeahead javascript file
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
$('#the-basics .typeahead').typeahead({
hint: true, //here i used typeahead js code though i didnt mentioned here
highlight: true,
minLength: 1
}, {
name: 'states',
source: substringMatcher(states)
});
You can simplify the PHP a little bit here when you read in the values as you dont need to increase the index:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);//making a connection
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myarray[] =$row["firstname"];
$myarray[] =$row["lastname"];//storing in the array
$myarray[] =$row["email"];
}
} else {
echo "0 results";
}
$conn->close();
?>
You could echo in the results to the Javascript where you require them, echo($myarray[0]) for example.
Your Javascript may look something like this:
var matches = <?php echo($myarray[0]); ?>
There are 4 ways you can do to insert dynamic content to your javascript code.
Make the javascript inline to your PHP page. That is, putting your js code inside <script> tags
Make the dynamic js variables global and populate them in your php page. Your separate JS files will be able to read these global js variables.
If you want to have a separate file for JS, you have to generate it everytime (because you cant have PHP code in javascript. The browser cannot interpret it, and the server cannot interpret it)
If you want to force the server to interpret PHP code in JS files, add a handler so that .js is handler by the php interpreter (whether php module or php-cgi) see Clean links to PHP-generated JavaScript and CSS
Related
I'm trying to get a value from the database and compare it with whatever id href was set. But nothing happens.
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "products";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo <<<EOT
<br>
<form action='index.php?$id' method="POST">
<input type='submit' name="submit" value="more">
</form>
EOT;
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
while($row = $result->fetch_assoc()) {
if ($_SERVER["QUERY_STRING"] == $row) {
echo 'you clicked something from the database' . $id;
}
}
}
$conn->close();
?>
Trying to eventually get a value from the database then individually show a description if the more href is clicked.
your answer has a high time complexity you can easily make you
SQL query
SELECT id FROM items WHERE id = ?
and if the rows number is 0 this is mean there is no record with this id
you can check row's number from num_rows
You will never see "you clicked something from the database" message because you already fetched the result from your query in the first loop, check this question why-cant-i-loop-twice-on-mysqli-fetch-array-results
An option is to save the result in an array to use it later in your second loop
//your first loop
$savedRows = [];
while($row = $result->fetch_assoc()) {
$savedRows[] = $row;
//the rest of your code
}
// ......
// your second loop
if (isset($_POST['submit'])) {
foreach($savedRows as $row) {
if ($_SERVER["QUERY_STRING"] == $row['id']) {
echo 'you clicked something from the database ' . $id;
}
}
}
Also note that if this is your actual code, you need to make the closing identifier of your herodoc EOT; the first character on it's line, otherwise the rest of the file will be part of this string
I have a PHP script in a server that returns {"available":true} or {"available":false}, depending on whether the email address is available or not. Here is the code:
<?php
$servername = "localhost";
$username = "root";
$password = "mysqlpass";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT username FROM testtable";
$result = $conn->query($sql);
$query = $_GET['query'].'#groupdesignace.com';
$arr = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$arr[] = $row['username'];
}
if (in_array($query, $arr)) {
$output = array('available' => false);
echo json_encode($output);
} else {
$output = array('available' => true);
echo json_encode($output);
}
} else {
echo "0 results";
}
$conn->close();
?>
On a different server where users are requesting their email address through a form, I am using Django. I have written the following code to check whether the email is available, if not, it should raise an error. Here is the code:
class RequestEmailAddressForm(forms.Form):
email = forms.CharField(label='Email', max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
def clean_email(self):
email = self.cleaned_data.get('email')
if email:
import requests
payload = {'query': email}
r = requests.get('http://172.16.16.172/check_email.php', params=payload)
result = r.json()
print r.url
status = result['available']
if status == False:
raise forms.ValidationError('This login name is unavailable!')
return email
Here is my view that is handling the form:
def request_email_address(request):
if request.method == "POST":
form = RequestEmailAddressForm(request.POST)
if form.is_valid():
data = form.cleaned_data
# do something here
else:
pass
return HttpResponseRedirect('/core/home/')
else:
form = RequestEmailAddressForm()
return render(request, "core/request_email_address.html", { "form": form })
However, the form is going to the submitted page but it is not raising validation error. What am I doing wrong?
You are doing nothing on if form is invalid. When ValidationError is raised django sets form.errors dict with data about what went wrong during validation. Read more https://docs.djangoproject.com/en/1.10/ref/forms/validation/
def request_email_address(request):
if request.method == "POST":
form = RequestEmailAddressForm(request.POST)
if form.is_valid(): # <- form validation is called on this line
data = form.cleaned_data
# do something here
# do redirect here
return HttpResponseRedirect('/core/home/')
else:
pass
else:
form = RequestEmailAddressForm()
return render(request, "core/request_email_address.html", { "form": form })
i'm trying to call getMensClothing() function from function.php to header.php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "khaki";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function getMensClothing(){
global $conn;
$sql = "SELECT * FROM men_clothing";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<li><a href='#' class='hvr-grow'>". $row['men_clo_items']." </a></li>";
}
}
}
header.php file looks like this
<?php include 'functions.php'; ?>
<?php
echo'
<div class="col-sm-2"><br>
<p> <b>Men\'s Clothing</b></p>
<ul>
'.getMensClothing().'
</ul>
</div>'
?>
function is called but the items aren't displayed where it has to everything is show at the top of the page . How to display the items inside the div ??
Use below Code
$html = "";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$html .= "<li><a href='#' class='hvr-grow'>". $row['men_clo_items']."</a></li>";
}
}
return $html;
into your function.php file
create a class like
class support{
//inside goes codes and functions
}
while calling into another file.
include it above file then create
$a=new support()
$a->functionname();
this should do the trick
What happens is that you use echo with parameters, that are evaluated to be printed.
You use concatenation with your arguments to echo.
You have one parameter contructed with the concatenation of three arguments.
The result of this concatenation is printed. One of these arguments is the returned value of the getMensClothing() function.
During the evaluation of getMensClothing() you print some data.
Consequently, the data printed in your function getMensClothing() gets printed before the end of the call to echo statement in header.php.
As other people pointed out, you should reconsider your technique as your code could be more easy to use if you separate the job of retrieving and constructing your data and the job of displaying it. Have a look to MVC for instance.
Not sure what I did wrong. I'm aware that having two fetch_assoc removes the first result but I don't have such a thing.
$sql = "$getdb
WHERE $tablenames.$pricename LIKE 'm9%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo $tableformat;
while($row = $result->fetch_assoc()) {
$name = str_replace('m9', 'M9 Bayonet', $row['Name']);
include 'filename.php';
echo $dbtable;
}
My connect file:
$servername = "";
$username = "";
$dbname = "";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
require_once ('seo.php');
$dollar = '2.';
$euro = '1.9';
$tableformat = "<div class=\"CSSTableGenerator style=\"width:600px;height:150px;\"><table><tr><th>Name</th><th>Price</th><th><a class=\"tooltips\">Community<span>New !</span></a> </th><th>Cash Price</th><th>Trend </th><th>Picture </th></tr></div>";
$getdb = "SELECT utf.id, utf.PriceMin, utf.PriceMax, utf.Name, utf.Trend , community1s.price as com_price, utf.Name, utf.Trend
FROM utf
INNER JOIN (select id, avg(price) price from community1 group by id) as community1s
ON utf.id=community1s.id";
$tablenames = 'utf';
$pricename = 'Name';
$idrange = range(300,380);
What happens is, it fetches the first two column's fine and the rest of the row is not there and pushes the other results down one row, which messes up the data.
Here's an image to demonstrate:
http://imgur.com/CQdnycW
The seo.php file is just a SEO function.
Any ideas on what may be causing this issue?
EDIT:
My Output:
echo $tableformat;
while($row = $result->fetch_assoc()) {
$name = str_replace('m9', 'M9 Bayonet', $row['Name']);
include 'filename.php';
echo $dbtable;
EDIT: Solved it by moving my variables around. Marked as solved.
I found the issue. Some Variables that did the output were in a bad place. Rearranged them and now they are fine.
Your HTML is broken, and strange things happen in broken tables. $tableformat contains HTML that opens a <div> and a <table>, but then closes the <div> with the table still open.
Fix the broken HTML and you'll probably find that all is well
In my table I have various requests each with their own reference number.
a user can see the number of requests on the page, but I want the user to be able to click on each request separately and be taken to a new page to see the specific details for that request.
I am trying to echo the reference in a hyperlink when the request is clicked and on the next page when I run my query to retrieve the name etc of that request it will only show the information which matches that reference number, i.e. 'SELECT * WHERE reference = $row['reference'].
However I am not sure on how to to do this, also I am concerned is this secure, if my query is checking against the reference in my url, i.e. mypage.php?reference=1234, whats to stop a user just manually typing in the url with a different reference number?
'mypage.php?reference=2468
the user should only be able to view the page if they actually clicked on the request, they should never be able to enter it directly into the url as this poses a security risk.
could I potentially mask my reference into a string? and echo out mypage.php?reference=$someString
page1.php
<div class="results_area">
<h44>Existing Supplier Request's</h44>
<?php
$conn = new mysqli($host, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "select * from new_supplier_request where status!= 'complete' AND action_taken='actioned'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<div class="table_header"><p>Request By</p><p>Date Requested</p><p>Status</p><p>Supplier Name</p><p>Description</p><p>Action</p></div>'; ?>
</div>
<div class="results_area"><?php
while($row = $result->fetch_assoc()) {
echo '<div class="request"><a href="ns_application.php?ns_request='.$row['reference'].'/">';
mypage.php
$reference = $row['reference'];
<?php
$conn = new mysqli($host, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "select * from new_supplier_request where status!= 'complete' WHERE reference = $reference Limit 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<h44>New Supplier Request: ' .$reference. ' </h44><br>';
echo 'The name of this supplier is, '.$reference['name'].';
} } ?>
</div>
You can use JavaScript to solve this problem.
I don't think that this will be 100% secure but actually it's more secure way than you are using now.
echo "<div .... onclick='showuniquereference('".$row['reference']."')'>"."</div>";
And Function like this
function showuniquereference(code)
{
var reference = code;
var form = document.createElement("form");
form.method = "POST";
form.action = "mypage.php";
var input = document.createElement("input");
input.name = "reference";
input.value = reference;
input.type = "hidden";
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
You can use this posted data to show unique reference to users.