No results displayed Mysqli - php

I have this query which is one of a number of queries I have done, All the other queries works great but this does not display any results. My database has results that meets the request. Someone tell me what could be wrong?
<?php include_once "/phpmysqli/config.php" ?>
<?php
$Week_ID = $teams->WeekID->CurrentValue;
$GKB = $teams->Keeper2->CurrentValue;
$stmt16 = mysqli_stmt_init($conn);
if (mysqli_stmt_prepare($stmt16,"SELECT Total_pts FROM keeper_points WHERE PlayerID=? AND WeekNo=?"))
{
mysqli_stmt_bind_param($stmt16,"ss",$GKB,$Week_ID);
mysqli_stmt_execute($stmt16);
mysqli_stmt_bind_result($stmt16,$GKB_pts);
mysqli_stmt_fetch($stmt16);
echo $GKB_pts;
mysqli_stmt_close($stmt16);
}
?>

It sounds like PlayerID and WeekNo columns may be integers.
If they are, then try passing in the parameters as so:
mysqli_stmt_bind_param($stmt16,"ii",$GKB,$Week_ID);

Related

how to loop through PHP code and MySQL?

How do I use the PHP loop through the query instead of putting all the result into an array then looping through the array
The way I use array and loop is like this:
<?php $userInfos = $qry->querySelect( SQL CODE HERE );
foreach($userInfos as $uInfo)
{
$fName = $uInfo['fName'];
$lName = $uInfo['lName'];
$gender = $uInfo['gender'];
?>
First name is: <? echo $fName; ?> and Last name is <? echo $lName; ?>.
<?php } ?>
I wanted to know better insight on how PHP loop through the query is better than array. Please redirect me to some example or possibly with MySQL code included.
How can I convert the above php code to be more efficient if I am pulling millions of record?
Thanks so much!.
You can do a simple loop with mysqli_fetch_row()
http://php.net/manual/en/mysqli-result.fetch-row.php
It looks like you need to use something other than the querySelect function (which appears to be returning an array).
Maybe the $qry object has some other function that will return you a statement handle you can fetch from, like the normal mysqli_ and PDO interfaces provide.
It looks to me like $qry is from a homegrown MySQL library "wrapper" class, which exposes a limited subset of the functions. If that object doesn't provide a way to get a statement handle, you may need to add the appropriate functions to the object definition, or abandon that and just use mysqli or PDO.
There's lots of examples of how to do that. With PDO, our first cut (before we add error checking and exception handling) might look something like this:
$sql="SELECT t.name FROM really_big_table t";
$sth=$dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC) ) {
echo "<br>Name is: ". htmlentities($row['name']);
}
$sth->close();
Reference: http://php.net/manual/en/pdostatement.fetch.php
I do the following:
//DB Query getData
$q_getData = "SELECT `stuff`, `moreStuff`, `otherStuff` FROM `table`";
$rsgetData = mysqli_query($DBi, $q_getData) or die(mysqli_error($DBi));
$row_rsgetData = mysqli_fetch_assoc($rsgetData);
$rows_rsgetData = mysqli_num_rows($rsgetData);
if($rows_rsgetData>0) {
do {
echo $row_rsgetData['stuff'] . ' ' . $row_rsgetData['moreStuff'] . '<br>';
echo $row_rsgetData['otherStuff'];
} while ($row_rsgetData = mysqli_fetch_assoc($rsgetData));
$rows = mysqli_num_rows($rsgetData);
if($rows > 0) {
mysqli_data_seek($rsgetData, 0);
$row_rsgetData = mysqli_fetch_assoc($rsgetData);
}
mysqli_free_result($rsgetData);
};
That runs the query and loops through each row until there are no rows left - only if there are rows returned in the first place. Once it's all finished it frees up the connection.

MYSQL & PHP trouble with echoing tables

So I am trying to echo out how many rows there are in a table with a COUNT command, but I purposely have no rows in the table right now to test the if statement, and it is not working, but worst, it makes the rest of the site not work(the page pops up but no text or numbers show up on it), when I added a row to the table, it worked fine, no rows = no work. Here is the piece of the code that doesn't work. Any and all help is highly appreciated.
$query1 = mysql_query("
SELECT *, COUNT(1) AS `numberofrows` FROM
`table1` WHERE `user`='$username' GROUP BY `firstname`,`lastname`
");
$numberofrowsbase = 0;
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
$enteries1 = $enteries1;
}else{
$enteries1 = $numberofrowsbase;
}
echo enteries1;
}
Seems you have over complicated everything. Some good advise from worldofjr you should take onboard but simplest way to get total rows from a table is:
SELECT COUNT(*) as numberofrows FROM table1;
There are several other unnecessary lines here and the logic is all bonkers. There is really no need to do
$enteries1 = $enteries1;
This achieved nothing.
Do this instead:
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
echo $row['numberofrows'];
}
}
Maybe against my better judgement, I'm going to try and give you an answer. There's so many problems with this code ...
Do Not Use mysql_
The mysql_ extension is depreciated. You should use either mysqli_ or PDO instead. I'm going to use mysqli_ here.
SQL Injection
Your code is wide open to SQL injection where others can really mess up your database. Read How can I prevent SQL injection in PHP? for more information.
The Code
You don't need to count the rows with a SQL function, especially if you want to do something else with the data you're getting with the query (which I assume you are since you're getting a count on top of all the columns.
In PHP, you can get how many rows are in a result set using a built in function.
So all those things together. You should use something like this;
// Connect to the database
$mysqli = new mysqli($host,$user,$pass,$database); // fill in your connection details
if ($mysqli->connect_errno) echo "Error - Failed to connect to database: " . $mysqli->connect_error;
if($query = $mysqli->prepare("SELECT * FROM `table1` WHERE `user`=?")) {
$query->bind_param('s',$username);
$query->execute();
$result = $query->get_result();
echo $result->num_rows;
}
else {
echo "Could not prepare query: ". $mysqli->error;
}
The number of rows in the result is now saved to the variable $result->num_rows, so you can use just echo this if you want, like I have in the code above. You can then go onto using any rows you got from the database. For example;
while($row = $result->fetch_assoc()) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo "$firstname $lastname";
}
Hope this helps.

MySQLi multi_query results for later use

I am using MySQLi multi_query to work with several select statemets at a time.
What i would like to know is how to handle results, so i will be able to use them later in code.
Example:
<?php
//connection stuff
$query = "SELECT name, surname FROM database1;";
$query.= "SELECT car, year, type FROM database2 WHERE carID='1';";
$query.= "SELECT product, price FROM database3;";
if ($mysqli->multi_query($query)) {
if($result = $mysqli->store_result()) {
while($row = $result->fetch_row()) {
--> what to do here?
}
}
}
?>
<html>
<div id='persona'>
<?php
foreach() {
--> print name + surname
}
?>
</div>
<div id='cars'>
<?php
foreach() {
--> print car + year + type
}
?>
</div>
<div id='product'>
<?php
foreach() {
--> print product + price
}
?>
</div>
</html>
One more thing, prepared statements are not possible when using multiple_query, right?
There really is no benefit in putting unrelated queries together in one multi query call. In fact, the risk of getting hit by a SQL injection is way bigger! The regular query function does only allow one query per call, so it is impossible to inject something into a SELECT statement, ending it prematurely and then add a DELETE.
With multi_query, this is possible.
Additionally, you have to fetch and end each query, and then it's gone. You you cannot change between the query results at will, they have to be fetched in exactly the order they were issued.
The better way is to just execute independent simple queries. This would allow you to use prepared statements as well, and as long as you are not getting HUGE amounts of data back, it will probably use the same amount of memory and not annoy anyone.

echo statement not showing result after getting variable from $_post in php mysql

I am unable to understand why I am unable to use echo statement properly here.
Link which passes get value to script
http://example.com/example.php?page=2&hot=1002
Below is my script which takes GET values from link.
<?php
session_start();
require('all_functions.php');
if (!check_valid_user())
{
html_header("example", "");
}
else
{
html_header("example", "Welcome " . $_SESSION['valid_user']);
}
require('cat_body.php');
footer();
?>
cat_body.php is as follows:
<?php
require_once("config.php");
$hot = $_GET['hot'];
$result = mysql_query( "select * from cat, cat_images where cat_ID=$hot");
echo $result['cat_name'];
?>
Please help me.
mysql_query returns result resource on success (or false on error), not the data. To get data you need to use fetch functions like mysql_fetch_assoc() which returns array with column names as array keys.
$result = mysql_query( "select
* from cat, cat_images
where
cat_ID=$hot");
if ($result) {
$row = mysql_fetch_assoc($result);
echo $row['cat_name'];
} else {
// error in query
echo mysql_error();
}
// addition
Your query is poorly defined. Firstly there is not relation defined between two tables in where clause.
Secondly (and this is why you get that message "Column 'cat_ID' in where clause is ambiguous"), both tables have column cat_ID but you did not explicitly told mysql which table's column you are using.
The query should look something like this (may not be the thing you need, so change it appropriately):
"SELECT * FROM cat, cat_images
WHERE cat.cat_ID = cat_images.cat_ID AND cat.cat_ID = " . $hot;
the cat.cat_ID = cat_images.cat_ID part in where tells that those two tables are joined by combining rows where those columns are same.
Also, be careful when inserting queries with GET/POST data directly. Read more about (My)Sql injection.
Mysql functions are deprecated and will soon be completely removed from PHP, you should think about switching to MySQLi or PDO.

Search entire table? PHP MySQL

I have made the following search script but can only search one table column when querying the database:
$query = "select * from explore where site_name like '%".$searchterm."%'";
I would like to know how I can search the entire table(explore). Also, I would need to fix this line of code:
echo "$num_found. ".($row['site_name'])." <br />";
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Thanks for any help, here is the entire script if needed:
<?php
// Set variables from form.
$searchterm = $_POST['searchterm'];
trim ($searchterm);
// Check if search term was entered.
if (!$serachterm)
{
echo "Please enter a search term.";
}
// Add slashes to search term.
if (!get_magic_quotes_gpc())
{
$searchterm = addcslashes($searchterm);
}
// Connects to database.
# $dbconn = new mysqli('localhost', 'root', 'root', 'ajax_demo');
if (mysqli_connect_errno())
{
echo "Could not connect to database. Please try again later.";
exit;
}
// Query the database.
$query = "select * from explore where site_name like '%".$searchterm."%'";
$result = $dbconn->query($query);
// Number of rows found.
$num_results = $result->num_rows;
echo "Found: ".$num_results."</p>";
// Loops through results.
for ($i=0; $i <$num_results; $i++)
{
$num_found = $i + 1;
$row = $result->fetch_assoc();
echo "$num_found. ".($row['site_name'])." <br />";
}
// Escape database.
$result->free();
$dbconn->close();
?>
Contrary to other answers, I think you want to use "OR" in your query, not "AND":
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
Replace other_column with the name of a second column. You can keep repeating the part I added for each of your columns.
Note: this is assuming that your variable $searchterm has already been escaped for the database, for example with $mysqli->real_escape_string($searchterm);. Always ensure that is the case, or better yet use parameterised queries.
Similarly when outputting your variables like $row['site_name'] always make sure you escape them for HTML, for example using htmlspecialchars($row['site_name']).
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Make sure that both forms use the same method (post in your example). The <form> tag should have the attribute method="post".
Also, what is wrong with the line of code you mentioned? Is there an error? It should work as far as I can tell.
A UNION query will provide results in a more optimized fashion than simply using OR. Please note that utilizing LIKE in such a manner will not allow you to utilize any indexes you may have on your table. You can use the following to provide a more optimized query at the expense of losing a few possible results:
$query = "SELECT * FROM explore WHERE site_name LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE other_field LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE third_field LIKE '".$searchterm."%'";
This query is probably as fast as you're going to get without using FULLTEXT searching. The downside, however, is that you can only match strings beginning with the searchterm.
To search other columns of table you need to add conditions to your sql
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
But if you don't know that I would strongly advise going through some sql tutorial...
Also I didn't see anything wrong with this line
echo "$num_found. ".($row['site_name'])." <br />";
What error message are you getting?
Just add 'AND column = "condition"' to the WHERE clause of your query.
Be careful with adding lots of LIKE % conditions as these can be very slow especially if using a front wild card. This causes the RDBMS to search every row. You can optimize if you use an index on the column and only a trailing wildcard.
You are searching the whole table, just limiting the results to those where the site_name like '%".$searchterm."%'. If you want to search everything from that table, you need to remove the WHERE clause
Here's the corrected line. You had a few too many quotes in it.
echo $num_found.".".($row['site_name'])." <br />";
Regarding displaying the message, you have a typo in your code:
// Check if search term was entered.
if (!$serachterm)
should be:
// Check if search term was entered.
if (!$searchterm)
In the code you have written, !$serachterm always evaluates to true because you never declared a variable $seracherm (note the typo).
your code is very bugy for sql injection first do
do this
$searchterm = htmlspecialchars($searchterm);
trim($searchterm);
next
$query = mysql_real_escape_string($query);
finaly your search looks like this
$query = "select * from explore where site_name like '%$searchterm%';

Categories