PHP loops works on localhost but on server - php

I have a weird problem. I read all related topic but there was no any solution for me. There are bunch of php codes on my project and all work perfectly but that one :
<?php
require("connection.php");
$query = "SELECT * FROM mrf WHERE completed=0 AND archive IS NULL ORDER BY projectname";
$get = $db->prepare($query);
$get->execute();
if ($get->rowCount()!=0){
foreach ($get as $res) {
'<li class="list-group-item"><span class="font-weight-bold">Product(s) : </span>';
$pieces = explode(",", $res['products']);
$pieces_count = count($pieces);
for ($i=0; $i <= $pieces_count -1 ; $i++) {
$query2 = "SELECT * FROM suppliers WHERE id = :id";
$get2 = $db->prepare($query2);
$get2->bindValue(":id",$pieces[$i]);
$get2->execute();
if ($get2->rowCount()!=0){
foreach ($get2 as $res2) {
echo $res2['name'].'<b>/</b>';
}
}
}
echo '</li>';
It works localhost perfectly but on server the result is empty.
I have checked the error(s)
error_reporting(E_ALL);
ini_set('display_errors', 1);
But there is no any error. Also If there had been an error, I would have seen it on localhost, because error_reporting works on localhost as well as on live server.
I checked typos, no any typo
Checked cpanel everything related to PHP. All is OK. By the way php ver is 5.6
Any idea??
-----------------------------------RESULT----------------------------
-I have checked all codes again and didn't find any error.
-I contacted my hosting company. They said my server has reached RLimitMEM (don't know what it is) So they increased my RlimitMEM value.
- I amnot satisfied with hosting company's answer but the code is working now.
- I appreciate for all answers and advices.

Replace your code with the following and check
<?php
require("connection.php");
$query = "SELECT * FROM mrf WHERE completed=0 AND archive IS NULL ORDER BY projectname";
$get = $db->prepare($query);
$get->execute();
if ($get->rowCount()!=0){
foreach ($get as $res) { ?>
'<li class="list-group-item"><span class="font-weight-bold">Product(s) :
</span>';
<?php
$pieces = explode(",", $res['products']);
$pieces_count = count($pieces);
for ($i=0; $i <= $pieces_count -1 ; $i++) {
$query2 = "SELECT * FROM suppliers WHERE id = :id";
$get2 = $db->prepare($query2);
$get2->bindValue(":id",$pieces[$i]);
$get2->execute();
if ($get2->rowCount()!=0){
foreach ($get2 as $res2) {
echo $res2['name'].'<b>/</b>';
}
}
}
echo '</li>';
}
}
You have not closed the PHP, closing curly braces were not there...

Try echoing it out:
foreach ($get as $res) {
'<li class="list-group-item"><span class="font-weight-bold">Product(s) : </span>';
Missing something there, no?
foreach ($get as $res) {
echo '<li class="list-group-item"><span class="font-weight-bold">Product(s) : </span>';
Sometimes it's the simple things.
Of note is PHP is perfectly fine with just having a useless string defined:
'foo';
Sandbox
It won't complain about that. For other languages this may be an issue, but PHP is very fault tolerant (sometimes to much so).
PS require("connection.php"); is not a function, while it will work with the () it's considered a bad practice. Instead require "connection.php"; works fine. This helps to differentiate it from a function when you glance at the code.
You should also move this around a bit:
foreach ($get as $res) {
//...
for ($i=0; $i <= $pieces_count -1 ; $i++) {
$query2 = "SELECT * FROM suppliers WHERE id = :id";
$get2 = $db->prepare($query2);
$get2->bindValue(":id",$pieces[$i]);
$get2->execute();
And do it like this:
$query2 = "SELECT * FROM suppliers WHERE id = :id";
$get2 = $db->prepare($query2);
foreach ($get as $res) {
//...
for ($i=0; $i <= $pieces_count -1 ; $i++) {
$get2->execute(['id'=>$pieces[$i]]); //instead of binding, you can just do it in execute too
And do the Prepare outside of the loop, this will improve performance in most cases. Every time you do a Prepare the DB is used to compile the query instructions, then when you execute it only the data is sent. This is how they defeat SQl Injection, because the SQL and the DATA are handled separately.
So by preparing it within the Loop you are asking the DB for unnecessary work. The format of the SQL does not change per/loop only the data does. Therefor, there is only the need to execute the query for each iteration.
Lastly:
Your missing two closing }} in your code for the question. Make sure to fix those syntax errors. I suspect they are just a omission in the question as you stated the code works locally.

Related

cannot select a row in mysql

EDIT1 : used double quotes and single quotes but I am getting same error.
EDIT2 : same query is returning me result in mysql shell
I am selecting a row from a table.
if(!isset($_GET['title']) || !isset($_GET['user'])){
echo "hi"; //something come here
}
else{
$title = $_GET['title'];
$title = mysqli_real_escape_string($conn,$title);
$user = $_GET['user'];
$user = mysqli_real_escape_string($conn,$user);
echo $title ;
echo $user ;
// tried giving value directly to test but no luck
$query = "SELECT * FROM site WHERE client=\"Chaitanya\" && title=\"werdfghb\" ";
$result5 = mysqli_query($conn,$query) or die(mysqli_error());
$count = mysqli_num_rows($result5);
echo $count ;
while($result9 = mysqli_fetch_array($result5)){
$kk=$result9['url'];
echo $kk ;
}
$page = $kk;
include ( 'counter.php');
addinfo($page);
}
In my database there is a row with columns title and client and the values I entered are in that row but when I echo count(no of rows) it is showing zero.
Is there anything wrong with code ?
The error you are getting is due to the line
$page = $kk;
in this code $kk is not declared previously. The defined $kk is in the while loop scope.
declare the variable like this in the outer scope from the while loop
...
$kk = null;
while($result9 = mysqli_fetch_array($result5)) {
$kk = $result9['url'];
echo $kk ;
}
$page = $kk;
...
Error on Fetching Data
You have to crack you SQl into smaller pieces and test the code like this.
run the query SELECT * FROM site without any where and get the count
run the query SELECT * FROM site WHERE client='Chaitanya' and get the count
SELECT * FROM site WHERE title='werdfghb' and check the count
Then run the whole query
And see the results. This way u can find out in where the issue is in your SQL code. I prefer you use the mysql client to execute this queries
As I pointed out in my comment, $kk is undefined in the $page = $kk;, since it is declared in the while loop.
Do something like:
$kk = ''; //can also do $kk=NULL; if you want.
while($result9 = mysqli_fetch_array($result5)) {
$kk=$result9['url'];
echo $kk ;
}
$page = $kk;
try this one
$client = "Chaitanya";
$title = "werdfghb";
$query="SELECT * FROM site WHERE client='".$client."' and title='".$title."' ";
you can also use this
$query="SELECT * FROM site WHERE client={$client} and title={$title} ";

PHP Array Population Working on XAMPP but not Server

Thanks a lot to anyone who can help me out! I've uploaded a gift-shop style website to a server running PHP v 5.4.19. The problem is that the image and page references that were fetched on xampp don't appear in the array on the server. Why is this and what is wrong with my code (apart from me not adopting msqli yet)?
function smallDisplay()
{
$query = mysql_query($con, "SELECT `imageSrcQ`, `productCode` FROM `products` WHERE `displayCode` >= 11 && `displayCode` <= 12");
while ($results_row = mysql_fetch_array($query))
{
$returned_results[] = array(
'productCode' => $results_row['productCode'],
'imageSrcQ' => $results_row['imageSrcQ']
);
}
return $returned_results;
}
$results = smallDisplay();
echo $results;
$x = 0;
foreach ($results as $result)
{
${'img'.$x} = $result['imageSrcQ'];
$x++;
}
echo $img0;
Edit: mysql_query does not take $con as the first argument, see: http://php.net/manual/en/function.mysql-query.php.
Change your code to:
$query = mysql_query("SELECT `imageSrcQ`, `productCode` FROM `products` WHERE `displayCode` >= 11 && `displayCode` <= 12");
and it should work.
As a note you might want to declare your $returned_results - array before the loop, and use the mysql_fetch_assoc() instead

Improve & Functionalize Queried Array

Need a little help, advise, or link to an example or useful tutorial so I can learn this. As I am very new to programming in general.
I have 11 Select boxes in a form named 'ore1' thru 'ore11' that send data up to $_POST.
This little block turns that into an array that is used in another function.
//function calculateValue($sellValue){ -- add when you figure it out
if(isset($_POST['submit'])){
$i = 11 //total number of select boxes
$pdquery = "SELECT * FROM ore
WHERE '".$_POST['ore1']."'
LIKE id";
$result = mysql_query($pdquery);
$oredata1 = array();
while ($row = mysql_fetch_row($result)) {
$oredata1 = $row; }
}
else {}
}
I'd like like to be able to use this one bit of code with all 11 Select boxes without having to copy it 11 times by getting
.$_POST['ore#']. //5th line
$oredata# = $row; //10th line
to replace # with the appropriate # depending on the select box it is used on.
Any tips?? Thanks in advance.
In your HTML:
<select name="ore[]">
...
</select>
<select name="ore[]">
...
</select>
In your PHP
if(isset($_POST['submit']) && isset($_POST['ore'])){
foreach($_POST['ore'] as $ore){
$ore = (int)$ore;
$pdquery = "SELECT * FROM ore WHERE id = $ore";
...
}
}
Also do not use mysql_* function since deprecation process has begun
for ($i = 1; $i <= 11; $i++) {
$ore = 'ore'.$i;
$pdquery = "SELECT * FROM ore WHERE '".$_POST[$ore]."' like id";
...
execute it in a for-loop - from 1 to 11. Then you can use the variable $i to access stuff.
// I assume that there is some MySQLi object called $mysqli already present. You'll have to create it if it does not
if(isset($_POST['submit'])){
$pdquery = 'SELECT * FROM ore WHERE id LIKE ?';
$oredata = array();
if($stmt = $mysqli->prepare($pdquery)) {
for($i = 1; $i < 12; $i++) {
$ore = 'ore' . $i;
if(empty($_POST[$ore])) {
continue;
}
$oreValue = (int)$_POST[$ore];
$stmt->bind_Param('i', $oreValue);
$stmt->execute();
$oredata[$i] = $stmt->get_result()->fetch_array(MYSQLI_ASSOC);
}
}
$stmt->close();
}
This does NOT take into consideration the fact that there might be more than just those eleven inputs. Using an array on HTML side would certainly be cleaner (And you'd just have to replace the for-loop with a foreach-loop and use the key instead of $ore)

PHP PDO AJAX Query not working, my eyes are crossing

I am re-writing a file that will dynamically build queries to search and match any word in an string passed by an ajax event...
I cannot get the thing to return data. It acts like everything worked perfectly, but it didn't. All I get in firebug is success: true..which is good because that means there wasn't an error but my SQL results aren't being passed.
I know this code is going to be all over the place for you guys, but it doesn't work...
I've spent most of the day re-working this code so its not pretty or perfect yet, I just want it to return search results again...
Bill, if you are reading this, I didn't get a chance to look into the %LIKE alternatives you suggested last week ha...still waiting on your book in the mail.
Sorry to dump a ton of code on you guys but I just can't see what's wrong here.
function CreateOptions($columns, $num_elements, $condition="AND") {
$colcount = count($columns);
$optionString = " ";
for ($ii=0; $ii < $num_elements; $ii++) {
if ($ii > 0)
$optionString .= " AND (";
for ($i=0; $i<$colcount; $i++) {
if ($i>0)
$optionString .= " OR ";
$optionString .= $columns[$i] . " LIKE '%:search$ii%'";
}
//$optionString .= ")";
}
return $optionString;
}
include_once('../sys/core/init.inc.php');
$json = array();
$result = array();
if (isset($_POST['searchTerm'])){
try {
$search = trim($_POST['searchTerm']);
$search = preg_replace('/\s+/', ' ', $search);
$search = explode(" ", $search);
$num_search_elements = count($search);
switch($_POST['category']) {
case ("account"):
$querySyntax = "SELECT
idAccount,
FirstName,
LastName,
Email,
Phone,
CCCity,
db_name.states.Abbreviation
FROM
db_name.account Right Join
db_name.states On
db_name.account.CCState =
db_name.states.ID
WHERE";
$cols = Array ("FirstName", "LastName", "Phone", "Email", "idAccount");
$querySyntax .= CreateOptions($cols, $num_search_elements);
break;
default:
break;
}
$querySyntax .= " LIMIT 50";
// Build and run query (change to execute)
$dbs = $dbo->prepare($querySyntax);
for($i=0; $i<$num_search_elements; $i++) {
if ($dbs->bindValue(":search$i", $search[$i], (is_int($search[$i]) ? PDO::PARAM_INT : PDO::PARAM_STR))) {
// yea i know... nothing here its all below still
} else {
die("BIND_ERROR");
}
}
$dbs->execute();
// Put the array together
$search_results = $dbs->fetchAll(PDO::FETCH_ASSOC);
//print_r($search_results);
foreach($search_results as $col=>$val) {
$result[$i][$col] = $val;
$i++;
//echo "$col >> $val";
}
$stmt = null;
$result["success"] = true;
}
catch (PDOException $e) {
$result["success"] = false;
$result["error"] = $e->getMessage() . " >> SQL: $querySyntax";
}
} else {
$result["success"] = false;
$result["error"] = "INVALID DATA";
}
header('Content-type: application/json');
echo json_encode($result);
Here is the generated SQL taken straight from Firebug when I tell it to echo the query:
SELECT
idAccount,
FirstName,
LastName,
Email,
Phone,
CCCity,
db_name.states.Abbreviation
FROM
db_name.account Right Join
db_name.states On db_name.account.CCState =
db_name.states.ID
WHERE
FirstName LIKE '%:search0%' OR
LastName LIKE '%:search0%' OR
phone LIKE '%:search0%' OR
email LIKE '%:search0%' OR
idAccount LIKE '%:search0%'
LIMIT 50
replace :search0 with "mar" you get this from my db in terminal and phpmyadmin:
1 Mar <my real name> myemail#email 1231231234 City FL
2 Martin Short mshort#movies.com 2147483647 Beverly Hills CA
4 Martin Short mshort#email.com 2146791243 Beverly Hills CA
5 Martin Short mshort#movies.coms 2146791243 Beverly Hills CA
Try using:
header('Content-Type: text/javascript');
Check your http results using something like Firebug/Network view - it might be returning correctly, just isn't getting parsed in Javascript.
Your problem could be in this line:
foreach($search_results as $col=>$val) {
$result[$i][$col] = $val;
$i++;
//echo "$col >> $val";
}
At this point in the code $i starts as the value of $num_search_elements, and counts upward from there. It is never re-initialized and set to 0 after a previous loop in the code which uses $i to count up to $num_search_elements.
What happens when you print_r($result) after the above loop? What happens when you print_r($search_results) before this loop? Do they match?
The above code could be replaced with:
foreach($search_results as $col=>$val) {
$result[][$col] = $val;
}
Which will index upward starting from 0.
Your problem comes from the SQL query you generate.
I would suggest you get your query out of PDO and try it in phpmyadmin or mysql console.
If it works there, then your php script is not generating the sql properly. If it's that case it'll be a lot of help if you show us the real sql query and the results from your database.
Edit:
Try replacing this:
for ( $i = 0; $i < $num_search_elements; $i++ ) {
if ( $dbs->bindValue(":search$i", $search[ $i ], (is_int($search[ $i ]) ? PDO::PARAM_INT : PDO::PARAM_STR)) ) {
With this
for ( $i = 0; $i < $num_search_elements; $i++ ) {
$var = ":search".$i;
if ( $dbs->bindValue($var, $search[ $i ], (is_int($search[ $i ]) ? PDO::PARAM_INT : PDO::PARAM_STR)) ) {
And see if it works.
The reson it was not working was because I had the bound search iterations (:search0...) in '' which turns it into a literal which will not match anything in the database.

i need a little help on foreach

This is my cats in mysql
cats_id cats_position cats_parentid
1 1> 0
2 1>2> 1
3 3> 0
4 1>2>4> 2
and i am trying to create a navigation like:
index > cars > fiat > punto
from
cat=4&parent=2&position=1>2>4>
I end up getting:
Index carcarcarcar
and my php knowledge is not enough to finish this code. can you help me please.
<?php
$position = trim($_GET['position']);
$pieces = explode(">", $position);
$i=0;
foreach($pieces as $piece){
$result = mysql_query("SELECT * FROM cats
WHERE cats_id='".$pieces[$i]."'");
while($row = mysql_fetch_array($result))
{
$piecesid[$i] = $row['cats_id'];
$piecesname[$i] = $row['cats_name'];
$piecesposition[$i] = $row['cats_position'];
}
$i++;
}
?>
Index
<?php $i=0; foreach($pieces as $piece){
if($i=0)
$parent=0;
else
$parent=$placesid[$i-1];
echo '<a href="cats.php?cat='.$piecesid[$i].'&parent='.$parent.'&position='.$piecesposition[$i].'">'.$piecesname[$i];
}
Your first error is a missing semicolon here:
$i++;
The second bug is a missing dot after $parent in the echo line:
'&parent='.$parent.'&position='
The third (unexpected end) error will become apparent when you started to indent your code correctly. It's also bad style to omit the curly braces, because that makes it more difficult to find precisely such errors.
And lastly: when posting on Stackoverflow, include the full error message (which always mentions the line number!)
I believe this is what he is looking for:
Create a mysql table with id, parent_id, and name fields.
When a category is a "child" of another, that others parent_id field should be set accordingly, I see you already have something to that effect.
Use this code, setting $cat via $_GET['cat'] or something.
<?php
$cat = mysql_real_escape_string($_GET['cat']);
$res = mysql_query("select id,name,parent_id from categories where id = '$cat'");
$breadcrumb = array();
while ($category = mysql_fetch_object($res) {
$breadcrumb[] = "" . $category->name . "";
if ($category->parent_id != 0) {
$res = mysql_query("select id,name,parent_id from categories where id = '{$category->parent_id}'");
}
}
echo join(" > ", array_reverse($breadcrumb));
?>
You have not closed your foreach in the last php section
<?php $i=0; foreach($pieces as $piece){
if($i=0)
$parent=0;
else
$parent=$placesid[$i-1];
echo '<a href="cats.php?cat='.$piecesid[$i].'&parent='.$parent'&position='.$piecesposition[$i].'>'.$piecesname[$i];
//Missing } here
?>
you're missing a } at the end. Just put a } after the last line like this:
echo '<a href="cats.php?cat='.$piecesid[$i].'&parent='.$parent'&position='.$piecesposition[$i].'>'.$piecesname[$i];
}
By the way, you don't need cats_position in your table.
To handle hierarchical data like this you can use a nested set (http://en.wikipedia.org/wiki/Nested_set_model) or just rely on the parent_id.
The advantage of this is, that you for example don't need multiple parameters in your get query. Instead of
cat=4&parent=2&position=1>2>4>
you then archieve the same with:
cat=4

Categories