i'm trying to figure this out for days and i can't find what the error might be.
This is my code:
<?php
$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
include 'conn.php';
class get_data extends connection{
public function __construct($page,$rows){
$s_page=mysql_real_escape_string($page);
$s_rows=mysql_real_escape_string($rows);
$this->get_all($s_page,$s_rows);
}
public function get_all($page,$rows){
$this->connect_to_db();
$tablename = $this->define_table_name();
$offset = ($page-1)*$rows;
$result = array();
$rs = mysql_query("select count(*) from $tablename");
$row = mysql_fetch_row($rs);
$result["total"] = $row[0];
$startq="select * from $tablename limit $offset,$rows";
$rs = mysql_query("select * from $tablename limit $offset,$rows");
$items = array();
while($row = mysql_fetch_object($rs)){
array_push($items, $row);
}
$result["rows"] = $items;
echo json_encode($result);
}
}
$getdata=new get_data($page,$rows);
?>
The Output is {"total":"3","rows":[]}
THE PROBLEM IS: the rows are empty but it counts how many rows are in the db meaning that the connection is good but the query for the row is not working any suggestions?
You are mysql_real_escape_stringing your parameters before establishing a connection to the database. mysql_real_escape_string needs an existing connection to the database to do its job. If there is none, it'll try to establish a connection by itself, which most likely fails, which means your parameters are null.
That should've been easy to figure out if you'd've enabled error reporting or would have debugged your app by simply var_dumping various variables here and there.
Related
I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>
Image for reference I just dont get where I am wrong. Can somebody help me with this? I feel stupid right now
function total_price() {
$total = 0;
global $con;
$ip = getIp();
$select_price = $con->query("SELECT * from shoppingcart WHERE IP_address='$ip'");
while($row = $select_price->fetch_assoc()) {
$pro_id = $row['Product_id'];
$quan = $row['Quantity'];
$query = $con->query("SELECT * FROM products WHERE prod_id='$pro_id'");
while($row2 = $query->fetch_assoc()) {
$row2['product_price'] *= $quan;
$productprice = array($row2['product_price']);
$values = array_sum($productprice);
$total += $values;
}
}
echo "₱: ".$total;
}
I think there your $con->query(...) fails and so you $select_price is FALSE and not an object with some member functions.
Check Out the documentation of $mysqli::query
http://php.net/manual/en/mysqli.query.php
If you want to get the sql error print the Result of $con->error.
For example:
$select_price = $con->query("SELECT * from shoppingcart WHERE IP_address='$ip'");
if($select_price == FALSE) {
echo "SQL-Error:".$con->error
exit;
}
while($row = $select_price->fetch_assoc()) {
...
if fetch_assoc fails there is a problem with your result set.
Problem ist that:
$query
or
$select_price
is not a valid Result-Set.
Reason could be that the Querys to the database fails.
you can check this by doing:
print_r($select_price);
print_r($query);
Should Output: Ressource ID #XX -> if not, check your Query direct agains SQL.
hope this helps
So I have this piece of code that is not returning anything (the echo returns nothing and should be returning two rows):
<?php
include "connection.php";
$cliente = $_POST["cliente"];
$select = "SELECT CLIENTE, NOMCLI FROM CLIX1 WHERE NOMCLI LIKE ? ORDER BY NOMCLI";
$stmt = odbc_prepare($con, $select);
//preparing the array for parameter
$prep_array = array();
$prep_array[] = "'%$cliente%'";
$rs = odbc_execute($stmt, $prep_array);
$nombres = array();
$clienteIDS = array();
//if prepare statement is successful
if($rs)
{
$i = 0;
while($row=odbc_fetch_array($stmt))
{
$cliente_id = trim($row["CLIENTE"]);
$nombre = utf8_encode(trim($row["NOMCLI"]));
$nombres[$i] = $nombre;
$clienteIDS[$i] = $cliente_id;
$i++;
}
echo json_encode($nombres) . "|" . json_encode($clienteIDS);
}
else
{
echo "error";
}
odbc_close($con);
?>
I know the problem is not the parameter pass on the odbc_execute() because even if I do this, it doesn't return anything(with %mich% it should display two rows):
$rs = odbc_execute($stmt, array("%mich%"));
Do you see anything wrong in this code?
Please let me know and thanks in advance.
UPDATE ------
I made the changes on the code that were suggested on the answer below and I am getting a new error now:
Warning: odbc_execute(): Can't open file %mich%
Where mich is the text entered to search on the database.
I found the following that may relate: ODBC prepared statements in PHP
$prep_array = array();
$prep_array[] = "'%$cliente%'";
$rs = odbc_execute($stmt, $prep_array);
I think the Double Quotes might be causing an issue.
I've been trying to get a series of nested loops working to select the database name from one table then query the selected table in that database, and add up the results and display the number of them and the database name.
I have gotten the code to work but it keeps displaying:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
I have tried every way possible I have found online to help, but none work.
$resulta = mysql_query("SELECT dbname AF012 FROM Customer");
while($data = mysql_fetch_array($resulta))
{
$db = $data[' dbname '];
$result = null;
$result2 = mysql_query("SELECT changemade FROM $db.orders");
//looping through the results
while($row = mysql_fetch_array($result2))
{
//checking if any record is 1,2 or 3
if( ($row[‘changemade’]== 1) || ($row[‘changemade’]== 2) || ($row[‘changemade’]== 3) ) {
//if any match the if adding 1 to the counter
$counter ++;
}
}
unset($result2);
echo $db." ".$counter;
echo "<br>";
$counter = 0;
$result = null;
$result2 = null;
}
All the database connections are made and work fine, so it has nothing to do with that. Any help would be great.
You need to introduce error handling, also you can streamline your code. The current point of failure is querying the database and fetching from it, so you can encapsulate it into a function of it's own which will also reduce your code:
function mysql_query_array($query)
{
if (!$result = mysql_query($query)) {
throw new Exception(sprintf('Invalid query "%s", error: %s.', $query, mysql_error()));
}
return function () use ($result) {
return mysql_fetch_array($result);
};
}
With that little helper function, your code is now more compact and it has actual error handling:
$queryA = mysql_query_array("SELECT dbname AF012 FROM Customer");
while ($data = $queryA())
{
$counter = 0;
$queryB = mysql_query_array("SELECT changemade FROM {$data['dbname']}.orders");
while ($row = $queryB())
{
if (in_array($row['changemade'], range(1, 3))) {
$counter++;
}
}
printf("%s %s<br>\n", $db, $counter);
}
This is caused by the fact that mysql_query return false if the query fails, so one of your query fails and mysql_fetch_array() gets a boolean. Try changing $db = $data[' dbname ']; to $db = $data['dbname'];
I am writing a script to access a specific detail about the user and I was hoping to make the database query be function.
function connectUser($ip) {
$q = "SELECT * FROM users where ID='$ID'";
$s = mysql_query($q);
$r = mysql_fetch_array($s);
}
But when I try and use it it will not access the row the way I want it to.
$user = '999';
connectUser($user)
echo $r['name'];
But if I put echo $r['name']; in the function it will work.
your function is not returning anything. add return $r['name'] at the end of function.
then echo connectUser($user);
thare are 2 major problems in your code
the function doesn't return anything and you don't assign it's result to a variable.
Your variables doesn't match. $ip doesn't seem the same variable with $ID
so, this one would work
function connectUser($id) {
$q = "SELECT * FROM users where ID=".intval($id);
$s = mysql_query($q);
return mysql_fetch_array($s);
}
$user = '999';
$r = connectUser($user)
echo $r['name'];
That's because the variable $r isn't being returned by the function, so it's never being set outside of the function. Here's what you should have:
function connectUser($ip) {
$q = "SELECT * FROM users where ID='$ip'";
$s = mysql_query($q);
return mysql_fetch_array($s);
}
And then outside have:
$user = '999';
$r = connectUser($user)
echo $r['name'];
You might also want to take a look at this question: prepared statements - are they necessary
This function is not working,
as you did not supplied the database connection into function,
and you did not return anything (PHP will return NULL)
Please understand what is variable scope first,
and the function
A workable example, can be like :-
function connectUser($db, $ip)
{
$q = "SELECT * FROM users where ID='$ID'"; // vulnerable for sql injection
$s = mysql_query($q, $db); // should have error checking
return mysql_fetch_array($s); // value to be returned
}
How to use :-
$db = mysql_connect(...);
$res = connectUser($db, "some value");