this is driving me crazy why aren't the results showing???
function runSQL($rsql) {
$connect = mysql_connect('localhost','xxx','xxx') or die ("Error: could not connect to database");
$db = mysql_select_db('xxx');
$result = mysql_query($rsql) or die ("Error in query: $query. " . mysql_error());
return $result;
mysql_close($connect);
}
$rsql = "SELECT * FROM subscriptions WHERE subscriptionID = 6 ";
runSQL($rsql);
$row = mysql_fetch_array($result);
echo $row['subscription'];
mysql_free_result($result);
You don't process your result ...
You call your function (runSQL) to execute the query and it returns the resultset, but you don't catch the resultset to work with it.
Use $result = runSQL($rsql); instead of runSQL($rsql);.
Also note that mysql_close($connect); is never called in your code, it's unreachable as the return occurs first.
If you close the connection before doing mysql_fetch_(assoc|array|etc) on it, those functions will likely fail. The connection should not be closed until you're done interacting with the database, including reading the data.
Related
I am using a PHP script to pull comments from my database to populate an app. How the database is set up is any secondary comments, ie replies to comments, will have a reply_id. The issue im seeing is all comments, regarless of replies, are seeing the same replies as the one comment that has it. I tried deleting the array with the secondary comments in it, but to no avail. Could someone point out where I failed to seperate the values?
// Create connection
$conn = mysqli_connect($servername, $username, $password,$db);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
$memory_id=$_POST['memory_id'];
$query ="Select * FROM comment WHERE memory_id= '$memory_id' and reply_id=''";
$dbquery = mysqli_query($conn,$query);
$query2= "Select * FROM comment WHERE memory_id='$memory_id' and reply_id='$comment_id'";
if($dbquery){
$result = array();
while($row = mysqli_fetch_array($dbquery))
{
$temp_array= array();
unset($temp_array['replys']);
$temp_array['user_id']=$row['user_id'];
$temp_array['comment_id']=$row['comment_id'];
$temp_array['text']=$row['comment'];
$comment_id= $row['comment_id'];
$temp_array['replys']=array();
$dbquery2 = mysqli_query($conn,$query2);
if($dbquery2){
while ($row2 = mysqli_fetch_array($dbquery2)){
$temp_array['replys'][]=array(
'user_id'=>$row2['user_id'],
'comment_id'=>$row2['comment_id'],
'text'=>$row2['comment']);
}//Feeds comments
array_push($result, $temp_array);
}
}//pulls initial command
echo json_encode($result);
}
else
{
$response["error"] = TRUE;
$response["error_msg"] = "No memory FOund";
echo json_encode($response);
}
?>
The second query is being executed with $memory_id having the value of $_POST['memory_id']. An easy solution is to move the $query2 line below $memory_id = $row['memory_id'], that way the second query will be executed with the correct memory_id value.
EDIT
A better solution is to prepare your queries instead. Check the mysqli_prepare function.
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 8 years ago.
Improve this question
I have made code without error for connection and data fetching but i don't know why result for query is bool(false)
<?php
$con=mysql_connect("localhost","root","","xyz");
echo "Connection made";
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
The code to query and execution is
<?php
include ("includes/connection.php");
$query="SELECT * FROM userdata ";
$result=mysql_query($query);
var_dump($result);
?>
Help needed here
You should use either mysql or mysqli. This is the main problem for the error
<?php
$con=mysqli_connect("localhost","root","","xyz") or die ("error in connection".mysqli_error($con);
?>
and use $result= mysqli_query($con, $sql) where $sql contains your query
As i stated in the comments, your echo up there to tell you you connected to the mysql server is not effective. I pulled out an old function from me to show you how to do it and make it clear where the error is.
$con = mysql_connect('localhost','root','');
$db = mysql_select_db('xyz',$con);
function OpenConnection(){
global $con;
global $db;
if (!$con){
die('cannot connect to server!');
}else{
if(!$db){
die('cannot connect to database!');
}
}
}
If you dont get anything back, you ll be good to go.
Don't use mysql_* functions they are depracted use mysqli or pdo instead.
You need to fetch results of your query with fetch functions like mysql_fetch_array() or mysql_fetch_row() to get results of your query. There are plenty of examples in PHP manual.
In your cause it would be something like this:
<?php
$con=mysql_connect("localhost","root","") or die("didn't connect to db");
mysql_select_db('name_of_your_db', $con);
$query="SELECT * FROM `userdata` ";
$result=mysql_query($query); //this returns resource ID that needs to be fetched
while($row = mysql_fetch_row($result))
print_r($row);
If $result is false it means that query failed it can be caused by several issues for example there is no DB selected, there is no connection etc.
I'd also give you better solution with PDO
<?php
$dsn = 'mysql:dbname=nameofyourdb;host=127.0.0.1';
$user = 'root';
$password = 'yourpass';
try
{
$db = new PDO($dsn, $user, $password);
foreach ($db->query("SELECT * FROM `userdata`") as $row)
print_r($row);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I have a PHP page with some Mysqli that I am attempting to convert from MySql. I think I've converted most of it correctly, but I am getting the following error message when I try to execute the code (below):
Connection was OK!
Warning: mysqli_stmt_num_rows() expects parameter 1 to be mysqli_stmt, object given in /quantityremaining5.php on line 25
9999
I'm a bit new to this, so please be gentle - what is that I'm doing wrong? thanks!
<?php
include 'quantitytest_config.php';
// Create connection to MySQL
$link = mysqli_connect($hostname, $username, $password);
// Check connection
if (mysqli_connect_errno($link))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else { echo "Connection was OK!\n";}
//select a database to work with
$selected = mysqli_select_db($link, "grace59_countdown");
// or die("Could not select countdown");
// use if TWO SEPARATE columns for date and time
//execute the SQL query and return records
$result = mysqli_query($link,
"SELECT items
FROM cases
WHERE datetime<=NOW()
Limit 1 ");
if(mysqli_stmt_num_rows($result) == 0){
echo "9999";
} else {
//fetch tha data from the database
while ($row = mysqli_fetch_array($result)) {
echo "Quantity:".$row{'items'}."<br>";
}
}
//close the connection
mysqli_close($link);
?>
Use mysqli_num_rows($result) or $result->num_rows. As the name indicates, mysqli_stmt_num_rows() is intended to be used with a mysqli_stmt object (as returned by mysqli_prepare()).
See the documentation.
I am trying to combine PHP and Javascript, so that I get my data from the db in psql. So far, I am able to obtain the column I need, and set an array equal to this data. And then I am equating a js array to this array. This can be seen in the following code:
<?php
// attempt a connection
$dbh = pg_connect("host=localhost dbname=db user=postgres");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "SELECT * FROM dataset";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
$arr = pg_fetch_all_columns($result, 1);
pg_free_result($result);
// close connection
pg_close($dbh);
?>
And here's the js part.
var data = <?php echo json_encode($arr); ?>;
I have a function, which adds a data point to the array. I can add it to "data" array in js, but how do I make it so that it reflects in the db?
Thanks in advance :)
i am trying to do a guestbook in php but i am having some problems with mysql_fetch_array function. I don't understand why. I try to debug by putting
die("Error ".mysql_error()) but nothing prints out. I guarantee that all my variables are correctly initialized.
Here is my code :
<?php
$nbmessagesPP = 10;
mysql_connect(HOST, USER,PASSWORD) or die( "Unable to connect to database");
mysql_select_db(DBNAME) or die ("Unable to select database!");
.......
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$first_msg = ($page - 1) * $nb_of_Page;
$query = 'Select * from livredor ORDER BY id DESC LIMIT '.$first_msg.', '.$nbmessagesPP;
$rep = mysql_query($query) or exit("Error in query".mysql_error());
$v = true;
while($v){
$v = ($data = mysql_fetch_array($rep) or die ("Error fetching the data : ".mysql_error()));
echo "<p>id -> ".$data['id']."</p>";
echo "<p>pseudo ->".$data['pseudo']."</p>";
echo "<p>messages ->".$data['message']."</p>";
echo "<hr/>";
}
mysql_close();
?>
Can someone help me ;)
Your code doesn't deal with errors or the last row correctly. When $v is false, it still goes on to print some data. It would be better rewritten as:
while (($data = mysql_fetch_array($rep))) {
echo
...
}
That forces the evaluation of the fetch before moving on to the printing.
The problem is that you're trying to access elements of the result that don't exist. mysql_fetch_array returns a regular array, with integer indices. What you want is mysql_fetch_assoc, which returns an associative array.
Edit: You also have the problem Chris describes, not dealing with the last row correctly.
Generally, if you're receiving an error saying "supplied argument is not a valid MySQL result resource" it means that your MySQL query has failed, therefor not returning a valid result resource.
Try to echo out $query before sending it through mysql_query(), then try placing the echo'd query into phpMyAdmin and see if it returns any results.
Ok i have found the problem.
The problem was that in another page i had a mysql_connection and in that page i was creating a new one.
I just catch the return value of mysql_connect function and then close it with mysql_close function at the end. Like this :
<?php
$link = mysql_connect(HOST, USER,PASSWORD) or die( "Unable to connect to database");
mysql_select_db(DBNAME) or die ("Unable to select database!");
.....
while($data = mysql_fetch_array($rep)) {//i do something here}
mysql_close($link);
?>
Thanks for your answers folks :)