PHP doesn't get results from database [duplicate] - php

This question already has an answer here:
Why does mysqli num_rows always return 0?
(1 answer)
Closed 6 years ago.
I want to make instant search (google like) on key up Jquery ajax must ass value from HTML input field to PHP and PHP must chec in SQL table named "title" for any words which Begin or Contain the written word/letter,if there isn't anything found it must print the results out in a div.
Here is an example:
The picture explains: Up is the input field and down box is the box for results to be printed,as we can see it is working,but PHP don't want to get data from SQL,and only printing the result for 0 value (Nothing Found) on Bulgarian language.
There is my code:
<?php
$hostname = "localhost";
$username = "shreddin";
$password = "!utf55jyst";
$databaseName = "shreddin_nation";
$connect = new mysqli($hostname, $username, $password, $databaseName);
$fsearch = "";
if (!empty($_POST['fsearch'])) {
$fsearch = $_POST['fsearch'];
$req = $connect->prepare("SELECT title FROM food_data_bg WHERE title LIKE ?");
$req->bind_param('s', $fsearch);
$req->execute();
if ($req->num_rows == 0) {
echo 'Не бяха намерени резултати!';
}
else {
while ($row = $req->fetch_array()) {
?>
<div class = "search-result">
<span class = "result-title">
<? php
echo $row['title'];
?>
</span><br>
</div>
<?php
}
}
}
?>
The code is working till else {...} only this part didn't work..;/
I tried to use echo some results after else {...} because i thought it was a problem with my code,but it didn't work either way ...Can somebody explain to me where is my mistake (with simple language please) i am not really good at coding exept with PHP.
I won't put Jquery and HTML here because all working fine there, the post method is all good, the problem is with the php. But of course if you need it to help me I will paste it with no problem.

Edited
$value = '%'.$fsearch.'%;
$req->bind_param('s', $value);
it will work :)

<?php
$hostname = "localhost";
$username = "username";
$password = "pass";
$databaseName = "dbName";
$connect = new mysqli($hostname, $username, $password, $databaseName);
$fsearch="";
if(!empty($_POST['fsearch'])) {
$fsearch = $_POST['fsearch'];
$req = $connect->prepare("SELECT title FROM food_data_bg WHERE title LIKE ?");
$value = '%'.$fsearch.'%';
$req->bind_param("s", $value);
$req->execute();
$req->store_result();
if ($req->num_rows == 0){
echo 'Няма резултати';
}
else{
echo 'ДАА';
}
}
FINALY !!! that is the final result,it is printing ДАА when there is a result found and Няма резултати when there isn't any results fixed it after 1 month of pain lol Thanks to everyone which helped me <3<3 <3 <3 <3

Related

Assign value from $data['id']; [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to assign the value of $data['id'] to a variable like this:
$totalfor = $data['id'];
but this is not working, the value is not passing to $totalfor
If i echo $data['id'], it gives the right value which is 85
i need the value of $data['id'] to use it into a Select query
Anyone know the correct syntax to achieve this ?
Thanks
Here is the code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$jury = get_active_user('accountname');
$totalfor = $data['id'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT total AS total FROM votestepone WHERE votefor = '$totalfor' AND votedby= '$jury'";
$result = $conn->query($sql);
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
$totalvote = $row["total"];
}
} else {
echo "0 results";
}
?>
<?php echo $totalvote; ?>
The error is : Undefined variable: totalvote
If i set
$totalfor = 85; --> it works
but i need to use the value coming from $data['id'];
I'm in a view page and $data['id'] is coming from:
$data = $this->view_data;
if I <?php echo $data['id']; ?> it show 85
mysqli_query returns false when there is an error not if there are no results. The error says $totalvote is undefined, not $totalfor so the query didn't find a single result.
var_dump($sql) and make sure the query is correct and it really does fetch a result row when run against your database.

fetch_assoc doesn't show first row of results

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

Give value to Database by Pressing button

So i ran into some trouble not to long ago. As a student i am relativly new to programming and thus i often visit sites like these for help. My question is how can i add value to database by pressing a button. For me the problem here is that the button has a javavscript function to print. So in other words i want the button to have 2 functions, one that prints the page (which i already have) and one that adds value to the database. The purpose to adding the value to database is so people can see that its already been printed before.
So essentialy what i am asking for is how can i give a button 2 functions (one which is Javascript) and show people that the button is used(in this case, that it has been printed). All help will be appreciated very much.
My code is as following:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='window.print()' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
This would aquire 2 tasks:
Is that you bind a function to the click handler of the button.
Although it is bad practice to use function calls directly, in your case this would be that you replace the window.print() by a custom javascript function.
In that javascript function, you execute the window.print() again, where-after you do the next step in the logic: sending data to PHP.
With ajax you can archieve this.
With a parameter in the function you can pass what the ID of the current row is, which need to be passed to PHP.
You need to create another PHP script, that will be called by tje AJAX script.
In that PHP script you will do the required updates to the database.
Ok There is a lot of ways you can do it but here is how i would do it :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
//first you call a custom javascript function after the 'onclick'. I believe you'll have to pass a variable as an argument (like $id).
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='print_table($id)' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
Then you write this function in the header of your page
<script>
function print_table(id)
{
//print your document
window.print();
//send your data
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://www.domaine.com/directories/printed_table.php?id=" + id;
xmlhttp.send();
}
</script>
Then you write your file printed_table.php where you store 1 if printed or 0 if not printed. I don't understand german so i don't know where you store your printed variable but it goes like this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$id = $_GET['id'];
$resultSet = $conn->query("UPDATE `orders` SET `printed` = 1 WHERE `id` = `$id`");
?>
This should work. Just be careful and check the $_GET['id'] before to use it for security purposes. like you can use the php function is_int(). Depending of the security level you need you might want to secure this code a little more.

SQL / PHP if NULL show else

We are trying to complete / fix the below code, We cant seem to do the following.
Check if 'Check_Activation' is set to 'NULL' within the Database
IF value is NULL direct the user to one of the forms (1,2,3)
And finally if the 'Check_Activation' has already been activated and isn't 'NULL' prevent user from accessing one of the 3 forms.
I know its basicly there but we can't seem to figure out the final bug.
Please have a quick look at the code below and if anyone notices anything that isn't right please advice us.
Paste Bucket / Version
Website URL
<?php
$username = $_POST['username'];
$activation_code = $_POST['activation_code'];
$activation_codeurl = $activation_code;
$usernameurl = $username;
$db_host = "localhost";
$db_name = "aardvark";
$db_use = "aardvark";
$db_pass = "aardvark";
$con = mysql_connect("localhost", $db_use, $db_pass);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_name, $con);
$checkcustomer = mysql_query("SELECT `Check_Activation` FROM `members` WHERE `Username` = '".$username."' & `Activation` = '".$activation_code."'; ");
$array = mysql_fetch_array($checkcustomer);
if (is_null($array['Check_Activation'])) {
$username = substr($username, 0, 1);
if($username == '1') {
$redirect_url='form-one.php?membernumber='.$usernameurl.'&activation_code='.$activation_codeurl;
} elseif($username == '2') {
$redirect_url='form-two.php?membernumber='.$usernameurl.'&activation_code='.$activation_codeurl;
} elseif($username == '3') {
$redirect_url='form-three.php?membernumber='.$usernameurl.'&activation_code='.$activation_codeurl;
}
header("Location:". $redirect_url);
}
else
{
?>
Try this, You need to fetch the row from table and then you can check the values,
$val = mysql_fetch_array($checkcustomer);
if (is_null($val['Check_Activation']))
instead of
$val = mysql_query($checkcustomer);
if ($val == 'NULL')
NOTE: Use mysqli_* functions or PDO instead of using mysql_* functions(deprecated)
before I get into the technicality of what your are trying to accomplish, I have some advice for your code in general. You should avoid using the mysql api as it is deprecated, and use the mysqli api instead. I think you will also find that it is easier to use.
Now for the code:
You have this line in your code which seems to be incorrect, $checkcustomer is a result set from your previous query, so why are you running it as a query again?
$val = mysql_query($checkcustomer);
You already have the result set so do this:
$array = mysql_fetch_array($checkcustomer);
And then take the value of Check_Aviation;
if (is_null($array['Check_Aviation'])) {
//Do Something
}
Should solve your issue

MySQL Find First Colum's String, Echo Second Column's

Firstly, Sorry for bad English :(
I want key system like steam, origin or uplay. I give keys to user, user write that code into input, and code will echo user's code.
I have 1 Table. 2 Columns in it. 2 Rows for 2 Column. Like this:
.----------------------.
| sifre | bizimkey |
|______________________|
| A5Sr2A | First Code |
|______________________|
| FaQ1fS | Scnd. Code |
|______________________|
If user enters A5Sr2A into Input, PHP Echos "First Code". If user enters wrong code, Just appear alert.
I tried so many codes. I can run the code like this:
<?php
if ($_POST['pass'] == "A5Sr2A") {
{
echo "First Code";
}
} else {
header('Location:index.html');
}
?>
But I don't want this. This is so challenging thing. I asked myself, "Why don't you use MySQL?"
I am trying 7 Hours. Really. I want to do that. I want learn MySQL. Please Help. THANKS!
<? ob_start(); ?>
<html>
<link rel=stylesheet href="style.css">
<table>
<tr>
<td>
<center>
<?php
$host = "localhost";
$user = "user";
$password = "pass";
$database = "db";
$con = mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_errno()) {
echo "ERROR";
}
$result = m ysqli_query($con, "SELECT sifre FROM keyler");
if ($_POST['pass'] == $ result) {
{
$mykey = m ysqli_query($con, "SELECT bizimkey FROM keyler");
echo $mykey;
}
} else {
header('Location:index.html');
}
mysqli_close($con);
?>
</center>
</td>
</tr>
</table>
</html>
<? ob_flush(); ?>
Okay, see below for a basic implementation example:
$host = "localhost";
$user = "user";
$password = "pass";
$database = "db";
$con=mysqli_connect($host,$user,$password,$database);
if(mysqli_connect_errno()!=0)//mysqli_connect_errno() returns 0 when there are no errors
{
echo "ERROR";
}
$sifre_test = mysqli_real_escape_string($con,$_POST['pass']);
$result = mysqli_query($con,"SELECT '1' FROM `keyler` WHERE `sifre`='".$sifre_test."'");
if($result!==false)
{
//If $result !== false, the query was successful, so we'll try to grab a row
$row = mysqli_fetch_assoc($result);
//$row will be null if there wasn't a row found where `sifre`=$sifre_test
if(!is_null($row))
{
$result = mysqli_query($con,"SELECT `bizimkey` FROM `keyler` WHERE `sifre`='".$sifre_test."'");
if($result!==false)
{
$row = mysqli_fetch_assoc($result);
$bizimkey = $row['bizimkey'];
echo $bizimkey;
}
else
{
die("bizimkey query failed");
}
}
}
else
{
die("sifre query failed");
}
For a better understanding and more examples, see the documentation links below:
mysqli_query
mysqli_fetch_assoc

Categories