PHP, Mysqli, SQL query to get value and display others - php

I'm trying to do something fairly complicated but I hope it makes sense in text.
So I have a link on a page which take me to post.php?postid=3
In my database there is a a field which is integer called camp_id. When for example I'm on a post which has the field camp_id with a value of 1, I want to display everything in the table that has the value of 1 in that field.
If I change the URL to post.php?postid=2 and that post has a camp_id of say 4, I would display a list of everything that has a camp_id of 4.
Anyway here is my code below and the current error at the bottom.
Here is my function:
public function getartfromcamp($campid)
{
$con = $this->db->OpenCon();
$campid = $con->real_escape_string($campid);
$stmt = "SELECT * from post WHERE camp_id = '$campid'";
$relatedlinks = $con->query($stmt);
if ($relatedlinks->num_rows > 1) {
$sql = $relatedlinks;
} else {
$sql = "No article";
echo "";
}
$this->db->CloseCon();
return $sql;
}
Here is the code on the page:
include 'postclass.php';
$postid = $_GET['postid'];
$article = new Post();
$relatedlinks = $article->getartfromcamp($postid);
?>
<div class='row'>
<?php
while ($row = $relatedlinks->fetch_assoc()) {
?>
<ul>
<ul>
<li><?php echo $row['article_name'];?></li>
</ul>
It seems to work with postid=1 but when I change it to something else I get the error below:
Fatal error: Uncaught Error: Call to a member function fetch_assoc()
on string in
C:\inetpub\wwwroot\local.test.co.uk\blog-example\camp1.php:18 Stack
trace: #0 {main} thrown in
C:\inetpub\wwwroot\local.test.co.uk\blog-example\camp1.php on line 18
Line: 18:
while ($row = $relatedlinks->fetch_assoc()) {

In function getartfromcamp, you are returning $sql string, instead of the connection object, when there is no result.
In this particular case, no result is coming, hence string is being returned. So it throws out error, as you are trying to run fetch_assoc on a string. You should let the function return connection object only, even if there are no rows being returned.
Change to following:
public function getartfromcamp($campid)
{
$con = $this->db->OpenCon();
$campid = $con->real_escape_string($campid);
$stmt = "SELECT * from post WHERE camp_id = '$campid'";
$relatedlinks = $con->query($stmt);
$this->db->CloseCon();
return $relatedlinks;
}
SideNote: You should switch to Prepared statements, to prevent SQL injection related issues.

Related

SQL query to update item quantity using PHP PDO

Good morning everyone
I am trying to update the table with the new quantity selected, when I run the following function, however, I get this error:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\xampp\htdocs\php_Assessments\shoppingList\model\functions_products.php:11 Stack trace: #0 C:\xampp\htdocs\php_Assessments\shoppingList\model\functions_products.php(11): PDOStatement->execute() #1 C:\xampp\htdocs\php_Assessments\shoppingList\controller\product_update_process.php(21): update_item('57', '3', '1') #2 {main} thrown in C:\xampp\htdocs\php_Assessments\shoppingList\model\functions_products.ph
Function to update the quantity, function_products.php:
<?php
function update_item($soldID, $orderedQuantity, $itemQuantity)
{
global $conn;
$sql = "UPDATE shopping_items.sold SET orderedQuantity = :itemQuantity WHERE soldID = :soldID";
$statement = $conn->prepare($sql);
$statement->bindValue(':soldID', $soldID);
$statement->bindValue(':orderedQuantity', $orderedQuantity);
$statement->bindValue(':itemQuantity', $itemQuantity);
$result = $statement->execute();
$statement->closeCursor();
return $result;
}
?>
product_update_process.php
<?php
// Require database connection
require('connection.php');
// Require function
require_once("../model/functions_products.php");
// Fetch the data required
$soldID = $_GET['soldID'];
$itemQuantity = $_POST['itemQuantity'];
$orderedQuantity = $_POST['orderedQuantity'];
if(empty($itemQuantity)) {
echo '<script type="text/javascript">alert("The quantity is required.")</script>' ;
// Redirect the browser window back to the add customer page
echo "<script>setTimeout(\"location.href = '../index.php';\",2000);</script>";
} else {
//call the update_item() function
$result = update_item($soldID, $itemQuantity, $orderedQuantity);
// Redirect the browser window back to the admin page
header("location: ../index.php");
}
?>
What could be the issue here?
Thanks for your assistance.
To add to #TangentiallyPerpendicular's comment, why are you binding to :orderedQuantity? This variable is not being used in your SQL statement, even though you have told the SQL engine to expect the variable. The column doesn't need to be a variable in order pass a variable to it.

My function returns false after moving to a new server

I got php fatal error after transfer server with php v5.6.19, before that I had no problem at all with following script
Fetch data from db table:
function get_department_list($mysqli)
{
$sql = $mysqli->query("SELECT * FROM `dept` ORDER BY `dept_id` ASC");
if($sql->num_rows > 0){
return $sql;
}else{
return false;
}
}
Populate data in HTML:
<ul class="department overflow-scroll text-center">
<?php
$shop = new Shop;
$depts = $shop->get_department_list($mysqli);
while($dept = $depts->fetch_object()){
echo '<li>'.$dept->dept_name.'</li>';
}
?>
</ul>
In the end I got an error:
Fatal error: Call to a member function fetch_object() on boolean in C:\xampp\htdocs\project\include\header.php on line 206
First, you are returning a boolean from your function. So, no wonder PHP says you so.
Second, you should keep the matters separated. a function that works with mysqli should keep all mysqli stuff inside. An return just an array, that can be used anywhere without the need to call mysqli functions again.
function get_department_list($mysqli)
{
$sql = $mysqli->query("SELECT * FROM `dept` ORDER BY `dept_id` ASC");
return $sql->fetch_all();
}
And then use not while but foreach
foreach ($depts as $dept) ...
Besides (and more for the people who may chance to land on this question looking for an answer to their question) you should always set proper error reporting for mysqli, like it shown in this answer
Update your while loop for that case when you get false from $shop->get_department_list() call
updated while like this check for $depts if any data then get $dept:
while($depts && $dept = $depts->fetch_object()){

Query empty if included

I have been performing a query inside my page -- say, page.php -- where I run a simple query.
Pseudo-code:
$request_unavailble = mysqli_query($mysqli, "SELECT * FROM my_table WHERE availble='0'");
When this is performed from within page.php, I get all results where availble is set to 0. However, if I run this from within a seperate included file, the data returns empty. In fact, mysqli_num_rows returns 0 when included.
What's going wrong, here?
Edit
The following function was added as an include (both as a function and alone)
function compte_messagerie()
{
$requetes_messagerie = mysqli_query($mysqli, "SELECT * FROM ".DB_PREFIX."messagerie WHERE lu='0'");
if(mysqli_num_rows($requetes_messagerie) == 0)
{
echo '<a id="messagerie" href="messagerie">'.AUCUN_NOUVEAU."</a>";
}
else if(mysqli_num_rows($requetes_messagerie) == 1)
{
echo '<a id="messagerie" href="messagerie">';
echo '<span>'.mysqli_num_rows($requetes_messagerie)."</span> ";
echo MESSAGES_SINGULIER."</a>";
}
else
{
echo '<a id="messagerie" href="messagerie">';
echo '<span>'.mysqli_num_rows($requetes_messagerie)."</span> ";
echo MESSAGES_PLURIEL."</a>";
}
}
When porting your query into a function, the MySQLi connection object in $mysqli went out of scope, and was therefore invalid inside the function. With display_errors enabled, I would expect you to see errors like:
Notice: undefined variable $mysqli
Warning: mysqli_query() expects parameter 1 to be resource, null given
The cleanest solution is to pass $mysqli into your function as a parameter, making it available to the function's scope
// Expect the MySQLi resource as a parameter...
function compte_messagerie($mysqli)
{
$requetes_messagerie = mysqli_query($mysqli, "SELECT * FROM ".DB_PREFIX."messagerie WHERE lu='0'");
if(mysqli_num_rows($requetes_messagerie) == 0)
{
echo '<a id="messagerie" href="messagerie">'.AUCUN_NOUVEAU."</a>";
}
// etc.....
}
Try this. Please check if the available table is require string value or integer.
$request_unavailble = mysqli_query("SELECT * FROM my_table WHERE availble= 0 ");
while($rows = mysqli_fetch_assoc($request_unavailble)){ // <- this will check if there some data fetch
// You put some code here
}

Codeigniter function returning an empty query

I have this function on my model, which receives a parameter so I can pre-load some information on the view page, but somehow is coming back empty:
function addTicket($idt)
{
//Db Connection
$DB2 = $this-> load-> database('DB2', TRUE);
if (!empty($idt)){
$query = $DB2->query ("
Select TROUBLE_ID, ASSIGNED_DATE, CREATOR, PROBLEM_DESCRIPTION, RESOLUTION, RESOLVED_DATE
FROM TABLE1
WHERE TROUBLE_ID = ".$idt."
");
if($query){
return $query->result_array();
}
else
{
echo 'No Queries to display';
}
}
else {echo 'No results to display';}
}
I have an Oracle DB with a ton of entries, but the query keeps coming back empty, Just in case I did an echo 'id:'.$idt.; to check if the ID is being passed. And yes it is.
Also Im getting this message:
Fatal error: Call to a member function result_array() on a non-object
On my view page i have this code:
foreach($results as $row){ }
And im getting this message now:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Any idea why this is not working?
Is this CodeIgniter? If so a better way to check for results is if($query->num_rows() > 0) { } rather than just if($query) { }
Also if its CodeIgniter make sure you have db_debug set to TRUE in the config/database.php otherwise you won't get to see the database errors.
For some reason the query is failing
$this->db->_error_message();
should tell you why
$this->output->enable_profiler(TRUE);
Should give you much more information about the query
Update:
$DB2 = $this-> load-> database('DB2', TRUE);
if (!empty($idt)){
$query = $DB2->query ("
change ^^ to vv
$DB2 = $this-> load-> database('DB2', TRUE);
if (!empty($idt)){
$query = $this->DB2->query ("
Finally I was able to fix this problem when in my query condition i used single quotes before double quotes, like this:
Select TROUBLE_ID, ASSIGNED_DATE, CREATOR, PROBLEM_DESCRIPTION, RESOLUTION, RESOLVED_DATE
FROM TABLE1
WHERE TROUBLE_ID = '" . $idt . "'

PHP List based on Form Selection: MDB2 Error: syntax error

I'm creating a table that outputs a list of country details based on a form selection but I keep getting this error: MDB2 Error: syntax error. How can I fix this type of error?
Here is my code:
<?php
$db =& MDB2::connect($dsn);
if(PEAR::isError($db)){
die($db->getMessage());
}
$table_name="country";
$db->setFetchMode(MDB2_FETCHMODE_ASSOC);
$country_id = mysql_real_escape_string($_GET["country_id"]);
// collect values from a form sent with method=get
$gdp = mysql_real_escape_string($_GET["gdp"]);
$population = mysql_real_escape_string($_GET["population"]);
$country_name = mysql_real_escape_string($_GET["country_name"]);
$gold = mysql_real_escape_string($_GET["gold"]);
$bronze = mysql_real_escape_string($_GET["bronze"]);
$silver = mysql_real_escape_string($_GET["silver"]);
$total = mysql_real_escape_string($_GET["total"]);
$sql = "SELECT * FROM $country WHERE country_id='$country_id'";
$res =& $db->query($sql); //MDB2 Error: syntax error
if (PEAR::isError($res)) {
die($res->getMessage()); //error printed here
}
?>
In your line "SELECT * FROM $country WHERE country_id='$country_id'", the variable $country is not defined, so it will render as e.g. "SELECT * FROM WHERE country_id='1'", hence the SQL error.
It looks like you meant $table_name, which has the value 'country'.
Since that appears to be defined just a few lines up, it would probably make more sense to just write it in the SQL statement directly, rather than having a variable, but maybe you have plans for that variable later...

Categories