this is my first question here so feedback on how to improve my questions would be appreciated.
I am trying to display records from a database using PHP.
Here is the code
<?php
$dbConn = new mysqli('localhost', 'twa037', 'twa037Dg', 'autoservice037');
if($dbConn->connect_error) {
die("failed to connect to the database: " . $dbConn->connect_error);
}
else
{
echo "success";
}
$sql = "select * from customer ";
if ($dbConn->query($sql) )
{
echo "query successful";
}
while($row = $sql->fetch_assoc()) {
echo $row['familyName'];
}
$dbconn->close();
?>
I am able to connect to the database and also the query appears to be working fine as it is displaying "success" and "query successfull".
However, I am getting this error
Fatal error: Uncaught Error: Call to a member function fetch_assoc()
on string
Before you guys suggest this could be a duplicate of another post, I have noticed that in the other posts they have used the same code as I have without an issue.
mysqli_query returns a result on that you can call fetch_assoc(). not on the querystring itself.
if ($result = $dbConn->query($sql) )
{
echo "query successful";
}
while($row = $result->fetch_assoc()) {
more informations you can find here
while($row = $sql->fetch_assoc()) <=> while($row = $dbConn->query($sql)->fetch_assoc())
May be this question will be sort of "stupid-questions", but still...
I'm new to PHP and SQL and I can't understand what I am doing wrong here:
if(isset($_POST[$logButton])) //Checking for login button pressed
{
//Retrieving information from POST method
$uid = $_POST['login'];
$upwd = $_POST['password'];
//SQL Connection
$mysqli = new mysqli('localhost', 'root', '', 'students');
if(!$mysqli)
{
echo "<h1 class='h1A'>Problem accured while connecting to the DB. " . mysqli_error($mysqli) . "</h1>"; //!!!Delete displaying error msg after dev.
}else
{
$sql = "SELECT * FROM login_data WHERE login = ? AND password = ?"; //SQL query
$stmt = $mysqli->prepare($sql) or die("error1"); //No error
$stmt->bind_param('ss', $uid, $upwd) or die("error2");//No error
$stmt->execute() or die("error3");//Giving DB query. No error
$result = $stmt->fetch() or die("error4".mysqli_error($mysqli)); //Putting query's result into assoc array. !!!Delete displaying error msg after dev. No error
echo print_r($result); //It prints out "11" ? ? ?
if(count($result['id']) < 1) //If no rows found.
{
echo "<h1 class='h1A'>Couldn't find account. Please, recheck login and password.</h1>";
die();
}elseif($result['id'] > 1)//If more then 1 row found.
{
echo "<h1 class='h1A'>Caught 9090 error. Contact the administrator, please.".mysqli_error($mysqli)."</h1>";
die();
}elseif($result['id'] == 1) //If only one row's been found.
{
$_SESSION['isLoggedIn'] = true;
redirectTo('/index.php'); //Declared function.
die();
}
}
}
Here is a part of handler function in lib.php file. This file is included to the html-page and the function is used. No errors displayed and when I print_r $result - it prints out 11. Can't get it.
Well, use print_r without echo :
print_r($result);
or pass second parameter to print_r function so it can return string:
echo print_r($result, true);
See http://php.net/manual/en/function.print-r.php for more info.
I am trying to get a mysql data from the table, here -
try
{
$stmt = $user->prepare("SELECT status FROM users");
$result=$stmt->fetch(PDO::FETCH_ASSOC);
if($result['status'] != "Y")
{
$error[] = "Some error warning!";
}
else
{
// Some php codes
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Here user is a class where prepare is db connection mysql prepare function. The error always prints - "Array!". I am new to php. Any help will be appreciated.
EDIT: I have managed to solve the problem.
You forgot the call of PDOStatement::execute(). See php.net for some examples.
Have you already tried this?
try
{
$stmt = $user->prepare("SELECT status FROM users");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result['status'] != "Y")
{
$error[] = "Some error warning!";
}
else
{
// Some php codes
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Regarding the Array! output: Did you post the whole code of your script? Were do you try to print the array $error?
i wrote a PHP Function but it does nothing at a specific point.. im new to php and my english is bad, sorry for that.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
if(!isset($count)) {
try {
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$count)");
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$count WHERE sc_stream='$id'");
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
the code runs every time until a specific point (i marked it in the code with // ------ SHOW HERE!!!! ------------ //)
in the sql table, currently there is no entry. so i should create a new row
whats wrong with that code?! :(
Your script wont insert a new row, because you have defined $count, it is a mysqli_result object. You have to check if there is a row, something you could do like this;
Instead of
if(!isset($count))
use
if(mysqli_num_rows($count) == 0)
Some explanation:
You have this in your code:
if(!isset($count)) {
This checks that your variable has been set, nor is empty, false, or 0. This condition ALWAYS return true because the variable is setted in line before, use mysqli_nuw_rows instead
Combining what other people have said, and looking at the logic of what you're doing, it looks like you have a few fundamental issues:
I've tweaked some variable names to make it clearer what you're getting an peppered the code with comments that describe the issues.
I've ignored the SQL injection issues.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$countQuery = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
$numberOfRowsReturnedByQuery = mysqli_num_rows($count);
if ( $numberOfRowsReturnedByQuery > 0 ) {
$valueOfCountInQuery = $countQuery [0]['count'];
}
if( $numberOfRowsReturnedByQuery == 0) {
try {
// In this situation it looks like you want to set up a value in "recent" - I.E. you didn't have a record.
// But think about it for a second - if you had no record in "recent" then how could "$valueOfCountInQuery" possibly be set?
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$valueOfCountInQuery )"); // makes no sense to use "$valueOfCountInQuery" - maybe you mean "0" (zero)
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// In this situation it looks like you want to update the value in "recent" - I.E. you DID have a record and you want to change it.
// But think about it for a second - the value of "$valueOfCountInQuery" is the value that you got from "count" on "recent". You are setting it to the same value that's already in there!
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$valueOfCountInQuery WHERE sc_stream='$id'"); // redundant
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
You did a mistake here, query returns array
try this
mysqli_query($con,"UPDATE recent SET count=$count[0]['count'] WHERE sc_stream='$id'");
You have set:
count=$count
but
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
Specify a proper value for count not a resource
to retrieve the actual result of the query you have to do something like
if ( $result = $con->query($sql)){ //perform the query
if ($result->num_rows == 1){
if ($row = $result->fetch_assoc()){
$count = $row['count'];
}
else{
echo "couldn't fetch result row";
}
else {
echo "expected one result row, got ".$result->num_rows;
}
}
else {
echo "query failed:".$sql;
echo $con->errno.' '.$con->error;
}
// if you have more than one result row
if ( $result = $con->query($sql))
while ($row = $result->fetch_assoc()){ //loop through the result(s)
$count = $row['count']
}
// procedural style
if ( $result = mysqli_query($con,$sql))
while($row = mysqli_fetch_assoc($result)){
The script below connects to the db (I get the connected successfully echo) but none of the data from the query is shown onscreen.
I assume the data must be somewhere as I do not get the error message.
Question: Where is the error in the script?
<?php
//connectdb();
$con = mysqli_connect("localhost","UN","PW");
if ( $con == "" ) { echo " DB Connection error...\r\n"; exit(); }
echo 'Connected successfully';
$result = mysqli_query($con, "SELECT graduation_year FROM wp_gfsept2013");
while($row = mysql_fetch_array($result))
if ($result === "") {echo "An error occurred.";}
{
echo $row['graduation_year'];
echo "<br>";
}
?>
Appreciate any help that can be sent my way, I'm a real newbie at this stuff.
Roger
Try adding an opening brace after while($row = mysql_fetch_array($result)) and a closing brace before the end of the script.
Is this not a syntax issue?? Why is there an IF clause after a WHILE clause but before the opening bracket for the WHILE loop block?
Additionally, you are trying to use mysql_fetch_array() instead of mysqli_fetch_array().
<?php
//connectdb();
$con = mysqli_connect("localhost","UN","PW");
if ( $con == "" ) { echo " DB Connection error...\r\n"; exit(); }
echo 'Connected successfully';
$result = mysqli_query($con, "SELECT graduation_year FROM wp_gfsept2013");
if ($result !== FALSE && mysqli_num_rows($result) > 0) { // Proper way to test for results
while($row = mysqli_fetch_assoc($result))
{
echo $row['graduation_year'];
echo "<br/>";
}
}
else {
die("Query Returned 0 rows...");
}
?>
Documentation: mysqli_result::$num_rows