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

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.

Related

PHP doesn't get results from database [duplicate]

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

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.

error in mysql query string [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
<form action = "index.php" method = "post">
username : <input type = "text" name = "uname" /><br>
password : <input type = "text" name = "pass" /><br>
submit : <input type = "submit" name = "submit" value = "submit" />
</form>
<?php
if(isset($_SESSION['id'])){echo $_SESSION['id'];}
if(isset($_POST['submit'])){
if ($_POST['submit'] == 'submit'){
$uname = $_POST['uname'];
$pass = $_POST['pass'];
$db = "davidedwardcakes";
$connect = mysql_connect('localhost', 'root', 'wtfiwwu');
$db_connect = mysql_selectdb($db, $connect);
if(!$db_connect){echo 'no';}
$query = "SELECT * FROM `users` WHERE uname ='$uname' AND pass = '$pass'";
$result = mysql_query($query, $connect);
if(mysql_num_rows($result) > 0){//echo 'index failed'; var_dump($result);}
while($row = mysql_fetch_array($result)){echo $row['uname']
. "<br>";
session_start();
echo 'peruse';
$_SESSION['id'] = $row['id'];}}
else{echo 'lol'; var_dump($query);}}
Whenever I want to login, i get the error:
string 'SELECT * FROM users WHERE uname ='brown' AND pass = 'kenji'' (length=61)
meaning that theres a problem with my $query. If I remove the $pass query from $query it works fine but doesn't when it is included. Can anybody help please.
Let me convert your code to MySQLi at least. MySQL is already deprecated.
<?php
/* ESTABLISH CONNECTION */
$connect=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase"); /* REPLACE NECESSARY DATA */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* REPLACE THE NECESSARY POST DATA BELOW AND PRACTICE ESCAPING STRINGS BEFORE USING IT INTO A QUERY TO AVOID SOME SQL INJECTIONS */
$uname=mysqli_real_escape_string($connect,$_POST['username']);
$pass=mysqli_real_escape_string($connect,$_POST['password']);
$query = "SELECT * FROM `users` WHERE uname ='$uname' AND pass ='$pass'";
$result = mysqli_query($connect,$query); /* EXECUTE QUERY */
if(mysqli_num_rows($result)==0){
echo 'login failed';
var_dump($result);
}
else {
while($row = mysqli_fetch_array($result)){
echo $row['uname'];
} /* END OF WHILE LOOP */
echo 'Successfully Logged-in.';
var_dump($query);
} /* END OF ELSE */
?>

live search with Jquery

I am trying to implement a live search on my site.
I am using a script somebody has already created. http://www.reynoldsftw.com/2009/03/live-mysql-database-search-with-jquery/
I have got the Jquery, css, html working correctly but am having troubles with the php.
I need to change it to contain my database information but everytime I do I recieve an error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\search.php on line 33
These are the details of my database:
database name: development
table name: links
Columns: id, sitename, siteurl, description, category
This is the php script
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "password";
$dbname = "links";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
if(isset($_GET['query'])) { $query = $_GET['query']; } else { $query = ""; }
if(isset($_GET['type'])) { $type = $_GET['type']; } else { $query = "count"; }
if($type == "count")
{
$sql = mysql_query("SELECT count(url_id)
FROM urls
WHERE MATCH(url_url, url_title, url_desc)
AGAINST('$query' IN BOOLEAN MODE)");
$total = mysql_fetch_array($sql);
$num = $total[0];
echo $num;
}
if($type == "results")
{
$sql = mysql_query("SELECT url_url, url_title, url_desc
FROM urls
WHERE MATCH(url_url, url_title, url_desc)
AGAINST('$query' IN BOOLEAN MODE)");
while($array = mysql_fetch_array($sql)) {
$url_url = $array['url_url'];
$url_title = $array['url_title'];
$url_desc = $array['url_desc'];
echo "<div class=\"url-holder\">" . $url_title . "
<div class=\"url-desc\">" . $url_desc . "</div></div>";
}
}
mysql_close($conn);
?>
Can anybody help me input this database info correctly? I have tried many times but keep getting an error. Thanks in advance.
EDIT: IT IS CONNECTING TO THE DATABASE WITHOUT AN ERROR. CHECK HERE http://movieo.no-ip.org/
the mysql_query() call is failing an returning false instead of a resource. My bet is that mysql_select_db() is failing. This should show the error:
mysql_select_db($dbname) or die('Couldn\'t select DB: '.mysql_error());
Compare: database name: development to $dbname = "links";
I think you should change it to the right name.
As well as changing the $dbname to development, check your two SQL statements. They are selecting from the table urls instead of links.

Categories