I'm trying to echo a phone number from my database using php but it keeps returning blank. I've been fiddling around with it all night and looking at various examples but I've not been able to get it to work. Can someone help me please?
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = 'SELECT phone FROM users WHERE ID = 29' ;
$results = mysqli_query($conn, $sql);
$row = mysqli_fetch_row($results);
echo $row['phone'];
Since your using mysqli_fetch_row it returns result enumerated array which means it returns the result row array staring from 0 offset.
Reference : http://php.net/manual/en/mysqli-result.fetch-row.php
ie.
$row = mysqli_fetch_row($results);
//Now $row columns can be accessed by $row[0] $row[1] and so on.
On the other hand if you use mysqli_fetch_assoc then the result will be returned as associative array ie key value pairs
Reference : http://php.net/manual/en/mysqli-result.fetch-assoc.php
ie.
$row = mysqli_fetch_assoc($results);
//Now you can use $row as $row['phone'], $row['id'] and so on
Related
This question already has an answer here:
How to fix Trying to access array offset on value of type null error
(1 answer)
Closed 1 year ago.
I am trying to use table data in a single row data as the value of an variable in my code below and i keep getting "Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\done\test1.php on line 29"
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT lev1 FROM ref where id=1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "lev1: " . $row["lev1"]. "";
}
}
$mamo=$row["lev1"];
$conn->close();
what I'm I dong wrong ?
Trying to access array offset on value of type null
It means that $row is null (in the $mamo=$row["lev1"]; line), therefore it cannot behave as an array.
If you're using while ($row = $result->fetch_assoc()), it will keep assigning values to $row until it can no more (because that's supposed to break the loop). After you reach the last result, $row will always inevitably be null.
I am trying to create a simple echo from a SELECT from DB.
It echos blank always.
Here is the code:
<?php
$username = "xxxx";
$password = "xxxx";
$hostname = "xxxx";
$conn = mysqli_connect($hostname, $username, $password, "xxxx");
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
$user = $_GET['user'];
$pass = $_GET['pass'];
$sql = "SELECT id FROM 'users' WHERE user='$user' AND pass='$pass'";
$retval = mysqli_query($conn, $sql);
echo($retval);
mysqli_close($conn);
?>
It would be greatly appreciated if someone could help and tell me what I am doing incorrectly :)
If it worked, you didn't get ID back, but a "mysqli_result" object.
Try print_r($retval) to see what you really got.
If it's a mysqli_result object, you need another step to get the data.
while ($row = $retval->fetch_assoc()) {
echo $row['id'];
}
According to the manual:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return TRUE.
Moreover, please note that a query that runs but returns zero results is still considered a "successful query" since the query did run in the database and an empty result set is a legitimate response. This means the query will still return a mysqli_result object.
As I understood the code so far, if you want to echo results returned you could use mysqli_fetch_array(), so your code would become:
/* numeric array */
$row = mysqli_fetch_array($retval, MYSQLI_NUM);
And you can echo it as:
echo $row[0];
or
/* associative array */
$row = mysqli_fetch_array($retval, MYSQLI_ASSOC);
And then you could echo as:
echo $row['id'];
Furthermore, you can use mysqli_fetch_assoc() to loop over your results or for fetching single row instance purposes, an example is:
while ($row = $result->fetch_assoc()) {
echo $row['id'];
}
Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in the resultset.
And if you want to check if your query has found any rows, you can use mysqli_num_rows
Which works as the following:
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($retval);
Do you know if you are connected to the database or not? You could try changing a value to see if the error comes up or not.
If thats not the issue this should work better:
$host = 'xxxx';
$user = 'xxxx';
$pass = 'xxxx';
$db = 'xxxx';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
$sql = "SELECT id FROM 'users' WHERE user='$user' AND pass='$pass'";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
$whateverString = $row['cakes'];
}
echo $whateverString;
Now lets say that you had a value in the mysql row called cakes that is equals to 5 then it will fetch that specific string from the row if the user and pass is correct.
So the value above will output "5" if the mysql value 'cakes' is 5.
Thanks for your answers, people!
I ended up with this:
$q=mysqli_query($con,"SELECT id FROM `users` WHERE user='$username' and pass='$password'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if(json_encode($data)== '[]'){
echo 'error';
}else {
echo json_encode($data);
}
?>
I'm trying to make a simple PHP script that fetches a table from my MySQL database and encodes the results in JSON, so I can use them later in Java.
This is my code:
<?php
$servername = "localhost:3036";
$username = "example_user";
$password = "example_password";
$conn = mysql_connect($servername, $username, $password);
if(! $conn) {
die("Could not connect: " . mysql_error());
}
$sql = "SELECT * FROM table_name";
mysql_select_db("database_name");
$retval = mysql_query($sql, $conn);
if(! $retval) {
die("Could not get data: " . mysql_error());
}
while($row = mysql_fetch_assoc($retval)) {
$output[]=$row;
}
print(json_encode($output));
mysql_close($conn);
?>
This just gives a blank page as output (error messages are set to display).
However, if I change json_encode($output) to json_encode($output[0]) (or any other number within the array's bounds), the output becomes that one $row array.
This is probably a really stupid question, but after about 3 hours of research I'm at my wit's end. Thank you for any help.
User #Joni led me to the solution.
Adding mysql_set_charset("utf8") fixed my issue.
As mentioned in this post: Why is this PHP call to json_encode silently failing - inability to handle single quotes?.
Try
echo json_encode($output) ;
It seems you have some utf8 character in your result set
add this statement before running your query
mysql_query('SET CHARACTER SET utf8');
Update
"mysql"
to
"mysqli"
and add
mysqli_set_charset($variável_de _conexão, 'utf8');
below the connection variable
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.
In this code I have used the prepared statement query, I want number of rows but in following code it returns me zero rows. plz tell me what is wrong in my code.
$servername = "localhost";
$username = "root";
$password = "";
$dbname="lamp";
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$contactno=mysqli_real_escape_string($conn,$_POST['contactno']);
$description=mysqli_real_escape_string($conn,$_POST['description']);
$email=mysqli_real_escape_string($conn,$_POST['contactemail']);
$subject=mysqli_real_escape_string($conn,$_POST['subject']);
$creationdate=mysqli_real_escape_string($conn,$_POST['creationdate']);
if(isset($_POST['status1']))
{
$status =$_POST['status1'];
}
if(isset($_POST['noteid']))
{
$id = mysqli_real_escape_string($conn,$_POST['noteid']);
}
$stmt=$conn->prepare("update notifications set subject=?,description=?
,status=?, creationdate=?,contactno=?,contactemail=? where id=? "); $stmt->bind_param("ssisisi",$subject,$description,$status,$creationdate,$contactno,$email,$id);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows >0)
{
echo "sucess";
header("Location: updategovermentnotification.php");
}
Since UPDATE query returns only true or false based on successful execution, so you need to do like below:-
need to use if(mysqli_affected_rows($conn)>0){ instead of if($stmt->num_rows >0){
OR
if($stmt->execute()){ $stmt->store_result();echo "sucess";header("Location: updategovermentnotification.php");}
The mysqli_stmt property you are looking for is $affected_rows. It contains the number of rows affected by an INSERT, UPDATE or DELETE statement.
The property $num_rows contains the number of rows returned by a SELECT query.