mysql_query SELECT do not give the desired result - php

The following code always displays
rows = 0
eventhough the table contains Ravi in the field 'to'. Does anyone know what is wrong with this code?
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE to = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$result = mysql_fetch_array($result);
echo $result["to"] + " " + $result["from"];
} else {
echo 'rows = 0';
}
} else {
echo 'empty for Ravi';
}
//} else {
//}
?>

to is a reserved word in MySQL, if you want to use it you must encase it in backticks:
.... WHERE `to` = ...

I have not look at your code but I recommend looking at
http://php.net/manual/en/intro.mysql.php
this before you continue to use mysql and not mysqli. It isn't that different but mysqli seems to have a wrapper over mysql and uses the "->" to instantiate new classes for a connection. If that makes any sense.

Try this:
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
echo $row["to"] + " " + $row["from"];
} else {
echo 'rows = 0';
}
} else {
echo "empty for $to";
}
//} else {
//}
?>
MYSQLI version + some adjustments:
<?PHP
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
$result = mysqli_query($link, $query);
if (mysql_num_rows($result)>0) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $row["to"]. "+". $row["from"];
}
}
ELSE {
echo 'rows = 0';
}
}
mysqli_close($link);
?>
I would like to credit #njk and #Wezy for their contribution with regard to the reserved word to in mysql. The WHILE loop is not necessary if the table events can only contain one "to" in this case "Ravi". I suspect that the number of events can be greater than one.

#Wezy has a point but let's do the troubleshooting:
As #JonathanRomer in his comment suggested, do:
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'") or die(mysql_error());
What does it say? Does it fail at all?
Or, just before mysql_query do:
die("SELECT *FROM `events` WHERE `to` = '$to'");
this will print faulty query being executed. Next, fire up mysql console or PHPMyAdmin and try executing this query manually.
Again, what does it say?

Actually, my main purpose was to encode this message and receive it on a mobile device by using JSON. This is the full code. For normal checking purpose, instead of using json_encode(*), the values can be displayed individually. This is the solution I got and it is working perfectly for receiving the data in an android app on which I am working.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$response = array();
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = mysqli_connect_error();
echo json_encode($response);
}
if(isset($_POST['to'])) {
$to = $_POST['to'];
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
if($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->store_result();
$i = 0;
if($stmt->num_rows > 0) {
$stmt->bind_result($rowto, $rowfrom, $rowevent);
$response["events"] = array();
while($stmt->fetch()) {
$events = array();
$events["to"] = $rowto;
$events["from"] = $rowfrom;
$events["event"] = $rowevent;
array_push($response["events"], $events);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No events found";
echo json_encode($response);
}
$stmt->close();
}
} else {
$response["success"] = 0;
$response["message"] = "Required fields are missing";
echo json_encode($response);
}
$mysqli->close();
?>

Related

PHP / MySql if '1' echo "Ok" else if '0' echo "No"

Phpmyadmin:
Phpmyadmin Image example
if (mysql_query("SELECT setup FROM users") === 1) {
echo "One";
} else if (mysql_query("SELECT setup FROM users") === 0) {
echo "Zero";
}
On register. As defined: 0.
If table shows 0, echo Zero.
Else if table shows ID 1, echo One.
How is this done?
Solution:
$setup = mysql_query("SELECT setup FROM users");
$row = mysql_fetch_assoc($setup);
if ($row['setup'] == 0) {
echo "Zero.";
} else {
echo "One!";
}
I think you need this
First of all use mysqli
//$connection = your mysqli connection. Dont use mysql
Then properly write query if you need admin row
$query = "SELECT `setup` FROM `users` WHERE `user_id`=1 AND `username` = 'admin'";
Then execute query
$result = mysqli_query($connection, $query);
Then search for $setup value
while($row = mysqli_fetch_assoc($result)){
$setup = $row['setup'];
}
Then echo what you need
if ($setup == 1) {
echo "One";
} else if ($setup == 0) {
echo "Zero";
}
See the docs. The 'Example (MySQLi Procedural)' example is similar to what you want.
Snippet:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Changing
$sql = "SELECT id, firstname, lastname FROM MyGuests";
to
$sql = "SELECT setup FROM users";
then
if (mysqli_num_rows($result) > 0) {
to your various if checks should suffice. Not the cleanest. Seems like you could just print out the value of setup? Good luck!

MySQLI LOOP DATA

I want to get all the records from the while loop. I'm unable to get all the rows from the query. It shows only the first row.
Is there anything I was going wrong in my code.
function Connect($DB_HOST = 'localhost', $DB_USER = 'root', $DB_PASS = '', $DB_NAME = 'bodhilms')
{
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
return $mysqli;
}
function GetCoeficient($coeficient = false, $con)
{
if(!$con)
return 0;
$result = array();
$sql[] = "SELECT * FROM users ";
if($coeficient != false)
$sql[] = "WHERE username = '".$coeficient."' ORDER BY u.id";
//print_r($coeficient);
$query = $con->query(implode(" ",$sql));
//print_r($query);
while($row = $query->fetch_assoc())
{
$result[] = $row;
}
return (!empty($result))? $result : 0;
}
$con = Connect();
$result = GetCoeficient($coeficient,$con);
$username = $result[0]['username'];
$firstname = $result[0]['firstname'];
$lastname = $result[0]['lastname'];
$email = $result[0]['email'];
First of all,to make sure the infomation of mysql is right,like port.
and I wonder the code of you $result = Getcourse($coeficient,$con);, how the var coeficient come from.Then
You can try the code below:
$mysqli=new mysqli("localhost","root","root","123");
$query="select * from test";
$result=$mysqli->query($query);
if ($result) {
if($result->num_rows>0){
while($row =$result->fetch_array() ){
echo ($row[0])."<br>";
echo ($row[1])."<br>";
echo ($row[2])."<br>";
echo ($row[3])."<br>";
echo "<hr>";
}
}
}else {
echo 'failure';
}
$result->free();
$mysqli->close();

Ajax post json response issue

I have an issue with ajax response. I am using custom query for fetch result from database. Json response always shows null value while query is running successfully. Here is my code:
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
while($fetch = mysql_fetch_array($query))
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
#Amandhiman i did not get what is the use of if statement with in the while
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
the mention code definitely works for you
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
Try with the below code, (mysql is deprected), working for me with my test database table (Debug it, var_dump $result, $result->fetch_assoc(), $result->num_rows)
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
try this
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
echo json_encode($arr);
}
First of all start session before playing with it on the top of page
session_start();
check your database connectivity.
Use print_r($arr) for testing your array();
first off all you are using session variable . to use session variable you need to initialize it by session_start()
you are using key in the array in this way it will return the last inserted record in the array . try this code
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
// if wants to use session then start session
session_start(); // else it will return null
$_SESSION['ID']= $fetch['id']; // i don't know why this ??
// $arr['id'] = $_SESSION['ID']; comment this
$arr[] = array('msg'=>'succsee','ID'=>$fetch['id']);
}
else
{
$arr[]= array('msg'=>'fail','ID'=>null);
}
}
echo json_encode($arr);
}

Handling error report

I am new in PHP so I have to apologize for such a dumb question, but I am not sure how to find the right answer. I should check if my final result is empty (if $sql found anything). If it didnt find I would like to get some notification example "The list is empty". That message will also be visible from Android app when I call the url?
<?php
$host = "";
$user = "";
$pwd = "";
$db = "";
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// query the application data
$sql = "SELECT * FROM lista WHERE Grad='".$_GET['grad']."' AND Predmet='".$_GET['predmet']."'";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
If mysqli_num_rows returns 0, you have no records.
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) == 0) {
$rows = "no rows found";
} else {
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
}
mysqli_close($con);
echo json_encode($rows);

php switching to mysqli: num_rows issue

I recently started updating some code to MySQL improved extension, and have been successful up until this point:
// old code - works
$result = mysql_query($sql);
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo $row['data'];
}
// new code - doesn't work
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]");
if($result->num_rows == 1) {
$row = $result->fetch_array();
echo $row['data'];
}
As shown I am trying to use the object oriented style.
I get no mysqli error, and vardump says no data... but there definitely is data in the db table.
Try this:
<?php
// procedural style
$host = "host";
$user = "user";
$password = "password";
$database = "db";
$link = mysqli_connect($host, $user, $password, $database);
IF(!$link){
echo ('unable to connect to database');
}
ELSE {
$sql = "SELECT * FROM data_table LIMIT 1";
$result = mysqli_query($link,$sql);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $row['data'];
}
}
mysqli_close($link);
// OOP style
$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table LIMIT 1";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
if($result->num_rows == 1) {
$row = $result->fetch_array();
echo $row['data'];
}
$mysqli->close() ;
// In the OOP style if you want more than one row. Or if you query contains more rows.
$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
while($row = $result->fetch_array()) {
echo $row['data']."<br>";
}
$mysqli->close() ;
?>
As it was said, you're not checking for the errors.
Run all your queries this way
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]");
if no errors displayed and var dumps are saying no data - then the answer is simple: your query returned no data. Check query and data in the table.
In PHP v 5.2 mysqli::num_rows is not set before fetching data rows from the query result:
$mysqli = new mysqli($host,$user, $password, $database);
if ($mysqli->connect_errno) {
trigger_error(sprintf(
'Cannot connect to database. Error %s (%s)',
$mysqli->connect_error,
$mysqli->connect_errno
));
}
$sql = "SELECT * FROM data_table";
$result = $mysqli->query($sql);
// a SELECT query will generate a mysqli_result
if ($result instanceof mysqli_result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$num_rows = $result->num_rows; // or just count($rows);
$result->close();
// do something with $rows and $num_rows
} else {
//$result will be a boolean
}
$mysqli->close() ;

Categories