Passing data between MySql and Objective C - php

I am working on a small social web application as a final project for my iOS class. I have a profile view controller where all the info about the user from the database is supposed to be displayed on the labels. The problem is that I don't really know the best way to do this. Here is my php script:
<?
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
// Create an array to hold our results
$arr = array();
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
//return the json result.
echo '{"users":'.json_encode($arr).'}';
?>
So here I get the info about all the users in the database. I am sure this is not the right way to go, so I guess I need to change the SQL query to retrieve the data for the current user only. But how can I do this? Should I put the username which I enter on the login page into an extra variable and then pass it with JSON to this php script and add the 'WHERE username = 'blabla' statement to the SQL query then? If so, how can I pass the variable to this script with JSON?
Can you please give me some sample code? Or is there a different way to do this?
Thank you so much!

<?php
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
$data = mysql_fetch_array($rs);
foreach($data as $rec){
echo "user: $rec<br>";
}
?>

Related

PHP MySQL JSON Login System

I'm currently working on a login system (which works great by using two text fields and the user is then redirected). However, as I am developing a mobile app, it would be much easier to do this in JSON, and I am not entirely sure where to start. What I am basically looking to do is to use a https post request (from my app) so it would request: https://www.example.com/login.php?username=username&password=password
I have created a basic sample, but it's not what I'm looking to do with regards to passing in a parameter via the URL as my code just currently looks for users in the MySQL database and outputs the users in JSON. What I want to be able to do is pass in the username & password parameters, via the URL, and then output a "success" or "error" JSON response if the username/password is in the database or not.
<?php
$host = "localhost";
$username = "root";
$password = "password";
$db_name = "test";
$con = mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$sql = "select * from test_table";
$result = mysql_query($sql);
$json = array();
if (mysql_num_rows($result))
{
while ($row = mysql_fetch_row($result))
{
$json['items'] = $row;
}
}
mysql_close($db_name);
echo json_encode($json, JSON_PRETTY_PRINT);
?>
Edit
I have now started working on another system, which is pretty much what I am looking to do (after I found an example here: http://www.dreamincode.net/forums/topic/235556-how-to-create-a-php-login-with-data-from-mysql-database/) except every time that I request something like https://www.example.com/login.php?username=root&password=password - I get the JSON error 1 code
<?php
$host = "localhost"; // Host name
$db_username = "root"; // Mysql username
$db_password = "password"; // Mysql password
$db_name = "test"; // Database name
$tbl_name = "test_table"; // Table name
// Connect to server
mysql_connect("$host", "$db_username", "$db_password") or die("cannot connect");
// Select the database
mysql_select_db("$db_name") or die("cannot select DB");
// Get the login credentials from user
$username = $_POST['username'];
$userpassword = $_POST['password'];
// Secure the credentials
$username = mysql_real_escape_string($_POST['username']);
$userpassword = mysql_real_escape_string($_POST['password']);
// Check the users input against the DB.
$query = "SELECT * FROM test_table WHERE user = '$username' AND password = '$userpassword'";
$result = mysql_query($query) or die("Unable to verify user because " . mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['total'] == 1) {
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else {
// username and password not found
// failed
$response["failed"] = 1;
// echoing JSON response
echo json_encode($response);
}
?>
Try to change following lines and it should works. I get it to work, as the way you describe it.
1- Here you will get URL parameters and sanitize.
$username = $_GET['username'];
$userpassword = $_GET['password'];
$username = mysql_real_escape_string($username);
$userpassword = mysql_real_escape_string($userpassword);
2- Here you count how many rows you have
Change $row = mysql_fetch_assoc($result);
to $total_rows = mysql_num_rows($result);
3- Here you check if you have at least 1 row.
And change if ($row['total'] == 1) { to if ($total_rows == 1) {
That should give output {"success":1}
Note1: This is to solve your request and question, but does not necessary means the right approach or perfect solution in general.
Note2: I would suggest you think of password hashing, post method in stead of get, use mysqli or PDO in sted of mysql and input sensitization and not use URL to pass username and password. I would suggest you look at this link it describes some of the things I mentioned in my note1.
http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL

php local connection mysql database

I try to make a simple IOS app that can connect to mysql database and read one table. But my php code does't work and really have no idea why, it's seems correct to me. The database is in a raspberry phpmyadmin server and the server works great.
I will put my code here and please tell me what's wrong.
<?php
$host = "192.168.2.193";
$db = "produtos";
$user = "root";
$pass = "1234";
$connection = mysql_connect($host, $user, $pass);
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//check to see if we could select the database
if(!dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM produtos";
$resultset = mysql_query($query, $connection);
$records = array();
//loop throught all our records and add them to our array
while ($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
echo json_ecode($records);
echo $resultset;
}
}
?>
Based on the question:
use mysqli_connect rather than mysql_connect because mysql_connect is deprecated and will not work someday. Also what is the the error you are getting? change your die() statement to something more helpful die(mysqli_error($connection));
Based on your comment:
That error would suggest that you either A) don't have the right IP address or B) there is a network issue between your host server and the SQL server, is this code running on the same server that is hosting the SQL database? if so then you can probably just use localhost for your $host

SQL Server Database Query with PHP

I need to get some data from a Microsoft SQL Server database at work. When I have the data I need, I need to make an Excel spreadsheet that can be saved locally on my computer.
I found PHPExcel which seems to do the job on the Excel part, but what about getting the data from the Database?
I can't seem to find anything that's recent. Only old tutorials.
Use this way to Fetch the Records :
<?php
$hostname = "192.168.3.50";
$username = "sa";
$password = "123456";
$dbName = "yourdb";
MSSQL_CONNECT($hostname,$username,$password) or DIE("DATABASE FAILED TO RESPOND.");
mssql_select_db($dbName) or DIE("Database unavailable");
$query = "SELECT * FROM dbo.table";
$result = mssql_query( $query );
for ($i = 0; $i < mssql_num_rows( $result ); ++$i)
{
$line = mssql_fetch_row($result);
print( "$line[0] - $line[1]\n");
}
?>
This will fetch each rows from the Data Retrieve and Print on the Page. Use your Required format into that. I mean, Use html Table to show the data in well format.
Use this code to get an data from Database.
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = '192.168.3.50';
// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'sa');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else{
echo "connected ";
mssql_select_db('Matrix') or die("Wrong DATAbase");
//mssql_query("SELECT Seq_no from dbo.Trans_R WHERE Seq_no = 000001",$link) or die("cannot execute the query");
$query = mssql_query("SELECT Tr_Date,Tr_Time,Tr_Data from Matrix.dbo.Trans_R");
$f = mssql_fetch_array($query);
echo $f['Tr_Date'];
}
?>
Can i know why Negative Vote??
He asked me to :
" but what about getting the data from the Database?"

Connect a different database on the log-in process only

The codes I'm working on are a bit confusing since I didn't make this one. But what I want to do is get the login information from a different database. I can't just modify the config.php of the database connection cause it will mess up the whole system.
I tried the trick to connect 2 databases by storing different variables on mysql_connect. But in this case, its a bit confusing.
Is there another way to just change the database connection only once in the logging in process?
login.php (the php file once the login info is submitted)
include("inc/config.php");
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to connect!");
$query = "SELECT * FROM clients WHERE name = '$name' AND password = '$password'";
$result = mysql_db_query($database, $query, $connection);
$date_in = date("Y-m-d");
$time_in = date("H:i:s");
$client_accesslogin = $name;
if (mysql_num_rows($result) == 1)
{
session_start();
session_register('time_in');
session_register('date_in');
session_register('client_accesslogin');
session_register('remoteaddr');
$_SESSION['time_in']=$time_in;
$_SESSION['date_in']=$date_in;
$remoteaddr = $_SERVER['REMOTE_ADDR'];
$ipaddr = $_SERVER['REMOTE_ADDR'];
$client_accesslogin = $_SESSION['client_accesslogin'];
session_register("client_id");
session_register("client_name");
session_register("client_email");
session_register("client_company");
list($clientid, $name,$first_name,$last_name, $pass, $email, $company) = mysql_fetch_row($result);
$client_id = $clientid;
$client_name = $name;
$fname=$first_name;
$lname=$last_name;
$client_email = $email;
$client_company = $company;
$cisloggedin = 'Yes';
session_register("cisloggedin");
session_register("fname");
session_register("lname");
header("Location: menu.php");
mysql_free_result ($result);
mysql_close($connection);
}
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to connect!");
$query = "SELECT * FROM admins WHERE name = '$name' AND password = '$password'";
$result = mysql_db_query($database, $query, $connection);
$date_in = date("Y-m-d");
$time_in = date("H:i:s");
$accesslogin = $name;
if (mysql_num_rows($result) == 1)
{
session_start();
session_register('time_in');
session_register('date_in');
session_register('accesslogin');
session_register('remoteaddr');
$_SESSION['time_in']=$time_in;
$_SESSION['date_in']=$date_in;
$remoteaddr = $_SERVER['REMOTE_ADDR'];
$ipaddr = $_SERVER['REMOTE_ADDR'];
$accesslogin = $_SESSION['accesslogin'];
session_register("client_id");
session_register("client_name");
session_register("client_email");
list($clientid, $name, $pass, $email) = mysql_fetch_row($result);
$client_id = $clientid;
$client_name = $name;
$client_name = "admin";
$client_email = $email;
$isloggedin = 'Yes';
session_register("isloggedin");
header("Location: menu.php");
mysql_free_result ($result);
mysql_close($connection);
}
else
{
mysql_free_result ($result);
mysql_close($connection);
header("Location: index.php");
exit;
}
?>
That works. But If I remove the included config.php and just add the connection:
$database = "invoices";
$user = "root";
$pass = "";
$hostname = "localhost";
It doesn't login. I don't get it. the inc/config.php has some codes with the connection but why can't i just add the connection itself without using include?
I'm doing to assume that there's a dedicated page for login processing?
In which case you can just make a new config.php and connect to that db only on the login page?
A bit of your code or structure would help.
mysql_select_db() function sets the active MySQL database.
Syntax
bool mysql_select_db ( string database_name [, resource link_identifier])
mysql_select_db() attempts to select existing database on the server associated with the specified link identifier.
Returns TRUE on success, or FALSE on failure.
We can select database in mysql server by using mysql_select_db function. mysql_select_db() selects the current active database on the server that is associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to set a link as if mysql_connect() was called without arguments.
Made a function to connect to your database, also to close your connection.
function connect(user, pass, location)
function disconnect()
then you connect to your first db, do your operations. Close it and then open a new connection to the other db and do also your operations.
If you want to maintain 2 connections at the time, you could save your instances to variables
and do:
mysqli_select_db($instance1, 'SELECT ...');
mysqli_select_db($instance2, 'SELECT ...');
Also escape your variables in your query :)

Unable to connect to MySQL database but able to connect to server

I am just using a basic code to connect to my Mysql database. I am able to connect to my server but not database. using sqlyog:
<?php
$username = "root";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username) or die("Unable to connect to MySQL");
$selected = mysql_select_db("project",$dbhandle) or die("Could not select project");
$sql = "SELECT image_small FROM images";
mysql_query($sql,$selected);
while($row=extract_row($sql))
{
echo $row['image_small'];
}
?>
where is password of database? mysql_connect should be used as:
mysql_connect("localhost", "mysql_user", "mysql_password");
otherwise it will be the default password that will be used
There are so many things wrong here.
1. Your have a blank password for the root user in your database.
2. You're using mysql_* which everybody know is subject to many hasck.
3. You're trying to "extract" a row from your SQL query.
Use PDO:
$DB = new PDO("mysql:host=localhost;dbname=project","root","root_password");
$sql = "SELECT image_small FROM images";
foreach($DB->query($sql, PDO::FETCH_ASSOC) as $row) {
echo $row['image_small'];
}
try to connect using the following statement
$selected = mysql_select_db("project");
// i think you have to provide password in here mysql_connect($hostname, $username,$password);
since it is localhost and user is root you could use like this
mysql_connect($hostname, $username,"");

Categories