Mysql query not returning any rows - php

I have a very simple script that pulls data from a mysql db, However when I run it there is no output, I am setting the get request to the correct value related to the row and when i run the SQL query in PHPmyadmin it runs as expected.
my code;
session_start();
require_once 'includes/sessions.inc.php';
require_once 'includes/config.inc.php';
if(!isLoggedIn())
{
echo "not logged in";
}
else
{
//Connect to DB
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);
$id = $_SESSION['userid'];
$contactid = $_GET['contactid'];
//Get Data from DB
$query = "SELECT id, First_name, Last_name, email_addres, phone_number, photo, owner FROM tbl_contcats where id = '$contactid';";
$result = mysql_query($query) or die(mysql_error());
echo '<img src="./contacts/'.$result['photo'].'"/><br>';
echo 'First name:'.$result['First_name'].'<br>';
echo 'Second name:'.$result['First_name'].'<br>';
echo 'Email Address:'.$result['First_name'].'<br>';
echo 'phone_number'.$result['First_name'].'<br>';
}
?>
ps; any feed back on how I can improve my code/clean it up is apericated

If you want to access the variables the way you're doing it, you'll first need to fetch an associative array of your results:
$rows = mysql_fetch_assoc($result);
Then you'll access the entries via
while ($row = mysql_fetch_assoc($result)) {
echo '<img src="./contacts/'.$row['photo'].'"/><br />';
echo 'First name:'.$row['First_name'].'<br />';
echo 'Second name:'.$row['First_name'].'<br />';
echo 'Email Address:'.$row['First_name'].'<br />';
echo 'phone_number'.$row['First_name'].'<br />';
}
What you're doing right now is trying to access variables from a MySQL resource that is returned by the query. The mysql_query itself doesn't return a raw result set. ;)

Related

Not able to insert the data from url to database in php

final.php
Here I am trying to get the data from the url using GET method and trying to insert into the database. I was able to insert the data for first few rows after that the data is not inserted. Can anyone help me regarding this?
when I try to run the url: www.myii.com/app/final.php?name=123&glucose=3232...
the data is not inserting.
<?php
include("query_connect.php");
$name = $_GET['name'];
$glucose = $_GET['glucose'];
$temp = $_GET['temp'];
$battery = $_GET['battery'];
$tgs_a = $_GET['tgs_a'];
$tgs_g = $_GET['tgs_g'];
$heartrate = $_GET['heartrate'];
$spo2 = $_GET['spo2'];
$rr = $_GET['rr'];
$hb = $_GET['hb'];
$ina22 = $_GET['ina22'];
$accucheck = $_GET['accucheck'];
$isactive = $_GET['isactive'];
$address = $_GET['address'];
$deviceno = $_GET['deviceno'];
$sql_insert = "insert into query (name,glucose,temp,battery,tgs_a,tgs_g,heartrate,spo2,rr,hb,ina22,accucheck,isactive,address,deviceno) values ('$name','$glucose','$temp',$battery','$tgs_a','$tgs_g','$heartrate','$spo2','$rr','$hb','$ina22','$accucheck','$isactive','$address','$deviceno')";
mysqli_query($sql_insert);
if($sql_insert)
{
echo "Saving succeed";
//echo $date_time;
}
else{
echo "Error occured";
}
?>
Query_connect.php
This is my database config php file.
<?php
$user = "m33root";
$password = "me3i434";
$host = "localhost";
$connection = mysqli_connect($host,$user,$password);
$select = mysqli_select_db('miiyy',$connection);
if($connection)
{
echo "connection succesfull<br>";
}
else {
echo "Error";
}
?>
Make sure that all columns can contain NULL so that not filled fields will stay NULL instead of throwing an error.
Try below to see mysql error:
mysql_query($sql_insert);
echo mysql_error()
Try these
In SQL
Change the table name of query to some other name. Because "query" is reserved in SQL
In code
if (!mysqli_query($con,$sql_insert ))
{
echo("Error description: " . mysqli_error($con));
}
else
{
echo "Success";
}
Use mysqli_error() function

Warning: mysql_query() [function.mysql-query]: Access denied for user ''#'localhost' (using password: NO)

Good morning,
I am running crazy trying one of the my first php codes with mysql. I have tested this on two servers, one hosted somewhere else and also using a local wamp server, the results are the same so I must have something bad in the code creating the connection or later when I run the query.
For wamp I have already verified the php.ini and also the MySQL privileges, in the code I am using the credentials stated there. I would appreciate some guidance.
<?php
// Function: connect to a database. Returns the database connection.
function connect_db($host, $id, $pwd)
{
$connection = #mysql_connect('localhost', 'username', 'password')
or die('connection problem:' . mysql_error());
mysql_select_db('database_db');
return $connection;
if (!$connection)
{
print ("internal error " . mysql_errno() );
}
}
//get names from form
$ID = $_POST['ID'];
$Event= $_POST['Event'];
$Date = $_POST['Date'];
$Time = $_POST['Time'];
$Venue= $_POST['Venue'];
$TypeID= $_POST['TypeID'];
$Score= $_POST['Score'];
$Member = $_POST['Member'];
//insert values
$myquery = "INSERT INTO Results(ID, Event, Date, Time, Venue, TypeID, Score, Member )VALUES('$ID', '$Event', '$Date', '$Time', '$Venue', '$TypeID', '$Score', '$Member')";
$answer = mysql_query($myquery);
if (!$answer) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $myquery;
die($message);
}
while ($row = mysql_fetch_assoc($answer)) {
echo "Your results were entered successfully";
echo "<br>";
echo $row['Id'];
echo $row['Event'];
echo $row['Date'];
echo $row['Time'];
echo $row['Venue'];
echo $row['TypeID'];
echo $row['Score'];
echo $row['Member'];
}
?>
You need to change 'username' and 'password' to your actual credentials in your mysql_connect call.
Unless of course, those are your desired credentials - then you need to ensure that the user actually exists and has permission to access the database.
As a side note, use of mysql_* functions is deprecated and it's recommended to use mysqli_* or prepared statements.
try to given access table to user :
grant all On [tabelName] to [userName];
example
grant all On mysql.* to root;

PHP show records from mysql

Im blocked at following part of code...
i have config.php page, with following code inside:
<?php
// Start the session (pretty important!)
session_start();
// Establish a link to the database
$dbLink = mysql_connect('localhost', 'USER', 'PASS');
if (!$dbLink) die('Can\'t establish a connection to the database: ' . mysql_error());
$dbSelected = mysql_select_db('DATABASE', $dbLink);
if (!$dbSelected) die ('We\'re connected, but can\'t use the table: ' . mysql_error());
$isUserLoggedIn = false;
$query = 'SELECT * FROM users WHERE session_id = "' . session_id() . '" LIMIT 1';
$userResult = mysql_query($query);
if(mysql_num_rows($userResult) == 1){
$_SESSION['user'] = mysql_fetch_assoc($userResult);
$isUserLoggedIn = true;
}else{
if(basename($_SERVER['PHP_SELF']) != 'index.php'){
header('Location: index.php');
exit;
}
}
?>
Now i have another page, with following code inside:
<?php include_once('config.php'); ?>
<?php foreach($_SESSION['user'] as $key => $value){ ?>
<li><?php echo $key; ?> <strong><?php echo $value; ?></strong></li>
<?php } ?>
That code show me all informations stored in database, one by one..
I want to show informations, individualy in my page, something like:
<?php echo $email; ?>
etcetera..
Can someone explain me how to do that?
Thank you
You should output it like
<?php echo $_SESSION['user']['email'] ?>
assuming that 'email' is the column name in the users table.
Just address the relevant field in the associative array:
<?php echo $value['email';?>
Use this in the config file:
$_SESSION['user']['email'] = mysql_fetch_assoc($userResult);
instead of this
$_SESSION['user'] = mysql_fetch_assoc($userResult);
in your code. You can pass as many columns you want to pass from your table.
And in another page use
foreach($_SESSION['user']['email'] as $key => $value)
instead of
foreach($_SESSION['user'] as $key => $value)
in your code.
Remember number of columns you pass in config file, all those columns should be called in this page.

Retrieve user input from database

I am trying to display the customer record from my database thats is determined by the id.
What I already have is a return where the id = 42. What I want to do is make it where the record returned is based on the id number that the user inputs on a previous page, which is $customerid. Any suggestions?
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
You can get the parameter passed to the PHP via GET or POST using $_GET["param_name"] and $_POST["param_name"] respectively.
So if your page is called using
http://path/to/page.php?id=99
You can get 99 in $_GET["id"]
Similar for POST.
Not having seen your form, I am assuming that you will POST the data.
Here is my suggestion for how to handle the data:
$id=isset($_POST['id'])&&is_numeric($_POST['id'])?$_POST['id']:false;
if ($id) {
$result = mysql_query("SELECT id,email FROM people WHERE id = $id;");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
} else {
echo "ERROR: No ID specified.";
}
Also, consider using PDO as mysql_* statements are depreciated. At the least, investigate how to prevent SQL Injection.
Try this:
search.php
<form action="show_record.php" method="post">
<input name="customer_id" />
</form>
show_record.php
<?php
// use $_REQUEST to get a parameter from POST OU GET request method
$id = isset($_REQUEST["customer_id"]) ? $_REQUEST["customer_id"] : 0;
$id = mysql_real_escape_string(); // prevent sql inject
$result = mysql_query("SELECT id,email FROM people WHERE id = '$id'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
So, you can request the page show_record.php from POST or GET, anyway the answer will be the same.
Via GET:
localhost/show_record.php?customer_id=42

I'm trying to retrieve data from mysql using php for my Flex Mobile application, but no luck

I am creating a login based application and this is what I have so far. I am trying to read each field into a separate textarea. I have tried to bind the data etc. I do get a output in the textarea, but it prints all the fields in one textarea. Please help.
<?php
selectDB();
function selectDB() {
$usertoken = $_POST['usertoken'];
//Database service vars
$databasehost = "localhost";
$databasename = "morerandom";
$databasetable = "random";
$databaseusername = "root";
$databasepassword = "root";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT username, useremail, firstname, lastname FROM $databasetable WHERE usertoken='$usertoken'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count)
{
$rows = array();
while ($row = mysql_fetch_object($result)) {
$rows[] = $row;
}
echo $rows[0]->username . "\n";
echo "\n";
echo $rows[0]->useremail . "\n";
echo $rows[0]->firstname . "\n";
$first = $rows[0]->lastname;
echo $first;
// echo "$lastname;"
}
else
{
echo 'Token not valid';
}
mysql_free_result($result);
mysql_close($con);
}
?>
What you are getting is just one string. There are better way to retrieve this kind of data from the server side(XML or AMF).
If you want to go ahead with your method then split the string using '\n' as a delimiter but check first that the server response is not 'Token not valid'.
So something like this should work:
First remove the echo "\n"; line under the echo $rows[0]->username . "\n";
var responseArray:Array = theStringResult.split('\n');
So now the responseArray stores the username at position 0, useremail at position 1, firstname at position 2 and lastname at position 3.
But again, you are sending data from the server as raw text and this is not the best way to do it. Check this link to see how this can be done using AMFPHP.

Categories