PHP retrieve data from table row and store to variable - php

i guess the questions says it all. The result of my query results into a row which will match the condition. I want to get each data from each table column and put into a variable.
$getinfo = "select
user_firstname,
user_middlename,
user_lastname
from tempuserinfo
where user_email ='$ead'
and activation_code='$eac'";
$query = mysql_query($getinfo, $db);
if(!$query) {
echo'something went wrong.';
} else {
//put them into variables
$firstname = mysql_fetch_object($query, 'user_firstname');
$middlename = mysql_fetch_object($query, 'user_middlename');
$lastname = mysql_fetch_object($query, 'user_lastname');
}

If you are getting multiple results, you can loop through them like this:
$getinfo = "select user_firstname, user_middlename, user_lastname from tempuserinfo where user_email ='$ead' and activation_code='$eac'";
$query = mysql_query($getinfo, $db);
while ($row = mysql_fetch_array($query)) {
$firstname = $row['user_firstname'];
$lastname = $row['user_lastname'];
}
If you are only getting one row back (make sure you add a LIMIT to your SQL statement), then you can use something like this:
$getinfo = "select user_firstname, user_middlename, user_lastname from tempuserinfo where user_email ='$ead' and activation_code='$eac'";
$query = mysql_query($getinfo, $db);
$row = mysql_fetch_array($query);
$firstname = $row['user_firstname'];
$lastname = $row['user_lastname'];

mysql_* function are deprecated. In documentation its recommended like in latest versions of PHP they are going to use mysqli_* or PDO.
Below are the script using mysqli for your question:
$mysqli = new mysqli("localhost", "root_user", "root_password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$getinfo = "select
user_firstname,
user_middlename,
user_lastname
from tempuserinfo
where user_email ='$ead'
and activation_code='$eac'";
if ($result = $mysqli->query($getinfo)) {
while ($row = $result->fetch_object()) {
$firstname = $row->user_firstname;
$middlename = $row->user_middlename;
$lastname =$row->user_lastname;
}
$result->close();
}
else
{
echo'something went wrong.';
}

an example with mysqli, mysql as this deprecated
$sql = "select user_firstname, user_middlename, user_lastname from tempuserinfo where user_email ='$ead' and activation_code='$eac'";
$query = mysqli_query($conn, $sql);
while($rs = mysqli_fetch_assoc($query)){
$user_firstname = $rs['user_firstname'];
$user_middlename = $rs['user_middlename'];
$user_lastname = $rs['user_lastname'];
}
if you want to have all fields in order to consult them later, add them to an array
$i=0;
while($rs = mysqli_fetch_assoc($query)){
$data[$i] = array('user_firstname'=>$rs['user_firstname'], 'user_middlename'=>$rs['user_middlename'], 'user_lastname'=> $rs['user_lastname']);
$i++;
}
print_r($data);

This should work:
$result = mysql_fetch_object($query);
$firstname = $result->user_firstname;
$middlename = $result->user_middlename;
$lastname = $result->user_lastname;
BUT:
Use MySQLi or PDO sintead mysql module is deprecated already

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
try {
$sth = $dbh->prepare("select user_firstname, user_middlename, user_lastname from tempuserinfo where user_email = ? and activation_code=?");
$sth->execute(array($ead,$eac));
$row = $sth->fetch(PDO::FETCH_BOTH);
$user_firstname = $row['user_firstname'];
$user_middlename = $row['user_middlename'];
$user_lastname = $row['user_lastname'];
} catch (PDOException $e) {
echo 'Database operation failed: ' . $e->getMessage();
}
Really, do learn to use PDO, because it is as easy as using mysql_*, but much safer and better.

Related

PHP Register Script - check user exists not working

I've got a problem with my PHP Registration Script that firstly checks, if the user exists.
It always outputs "false".
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$database = #mysql_connect("***********", "********", "******") or die("Can't connect to the server. Error: ".mysql_error());
//$username = mysql_real_escape_string($username);
$passwort = hash("sha256", $passwort);
$numrows = mysql_query("SELECT * FROM *******.mikgames WHERE username='".$username."' LIMIT 1");
$checkuserexists = mysql_num_rows($numrows);
if($checkuserexists==0) {
$abfrage = mysql_query("INSERT INTO *******.mikgames (username,passwort) VALUES ('$username', '$passwort')");
echo'true';
}
else {
echo'false';
}
?>
Edit: Now I'am using MySQLi and I've changed the code into this:
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$con = mysqli_connect('************','******','******') or die(mysqli_error());
mysqli_select_db($con, "*******") or die("cannot select DB");
$passwort = hash("sha256", $passwort);
$query = mysqli_query($con,"SELECT * FROM *******.mikgames WHERE username='".$username."'");
$result = mysqli_num_rows($query);
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames (username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
echo 'true';
}
else {
echo 'false';
}
?>
And it works.
You could go one step better and take an OOP approach using the PDO driver; PDO invokes security by allowing secure parameter binding and uses the SQL preferred functions.
Inside your pdo_driver.php file:
namespace ProjectName\App\Drivers;
if(!defined('IN_PROJECTNAME'))
{
die('No Script Kiddies Please...');
}
interface EntityContainer
{
public function query($statement, array $values = array());
}
class Entity extends \PDO implements EntityContainer
{
public function __construct(
$dsn = 'mysql:host=XXXX;dbname=XXXX', $user = 'XXXX', $pass = 'XXXX'
) {
try {
parent::__construct($dsn,$user,$pass);
} catch (PDOException $ex) {
die('FATAL ERROR: ' . $ex->getMessage());
}
}
public function query(
$statement, array $values = array()
) {
$smpt = parent::Prepare($statement);
(empty($values)) ? $smpt->execute() : $smpt->execute($values);
return $smpt;
}
}
Inside any other php file:
define('IN_PROJECTNAME', 0);
require_once dirname(__FILE__) . '/path/to/pdo_driver.php';
$container = array();
$container['Connection'] = new ProjectName\App\Drivers\Entity();
$username = $_GET['username'];
$passwort = $_GET['passwort'];
if(empty($container['Connection']->query('SELECT passwort FROM ******.mikgames WHERE username = ?', [$username])->fetch()['passwort'])) {
$container['Connection']->query('INSERT INTO ******.mikgames (username,passwort) VALUES (?, ?)', [$username,$passwort]);
}
Two Factors:
Firt Factor
You need to add an error output for debugging purposes:
$query = mysqli_query($con,"SELECT * FROM <tablename> WHERE
username='".$username."'") or die(mysqli_error($con));
I can't see a clear error with the information you have displayed here so far so you should also check what the value of $username acutally is and how closely it fits the value in the DB. Also read and take on board what the error output tells you.
Second Factor:
Your problem is you're running/articulating a query twice, here:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
You see $abfrage is a MySQL result object and you're then plugging it back into a MySQL query call, with the variable declaration $result. So your result is querying a query. This is an error.
What you probably want to do is use MySQLi_affected_rows to count how many rows have been inserted and run the appropriate IF clause:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_affected_rows($con);
echo 'true';
}
else {
echo 'false';
}
Use #mysql_***** for your ptoject.
$sql="SELECT * FROM table_name";
$result=#mysql_query($sql, $conn);
while ($name = # mysql_fetch_array($result)){
echo $name ['username'];
}
You just used simple mysql_***

android - php fetch mysql data by user id

This my PHP URL for fetching the data from MySQL. I need to make mysqli_fetch_array code saying if filled uid in the app-data table is the same with uid in users table fetch the data from all row in app-data to the uid like every user show his items from app-data table.
$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());
}
$sql = "SELECT * FROM app_data ORDER By id";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
I think this is the correct answer:
<?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());
}
$sql = "SELECT * FROM app_data WHERE u_id=".$_POST['posted_uid']." ORDER By id";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
Little tip for the future:
Don't search exactly what you want, only search in parts.

PHP, mySQL. saving on more than one different table using php action script

I am working on one php script and would like to insert data to three different tables. How can I do that on php action script.
error_reporting(0);
$datee=$_POST['date'];
$company=$_POST['company'];
$PAddress = $_POST['PAddress'];
$recruiter=$_POST['recruiter'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$company=$_POST['company'];
$agents=$_POST['agents'];
$resumes = $_POST['resumes'];
$structure=$_POST['structure'];
$sql = "INSERT INTO job_spec_contact (contact_info_key, datee,company_name,Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone')";
"INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
The problem is, it is only saving date on one table.
please assist me as I am new to php.
Thanks in advance.
$link = mysqli_connect("host", "username", "password", "database");
$sql = "INSERT INTO job_spec_contact (contact_info_key, datee,company_name,Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone') ;";
$sql . = "INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
mysqli_multi_query($link, $sql);
Sorry for late reply.
If you are using mysql: (Not recommended due to unsecure)
$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('YourDBName') or die("cannot use database");
if(isset($_POST['Submit'])){
$datee = $_POST['date'];
$company = $_POST['company'];
$PAddress = $_POST['PAddress'];
$recruiter = $_POST['recruiter'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$company = $_POST['company'];
$agents = $_POST['agents'];
$resumes = $_POST['resumes'];
$structure = $_POST['structure'];
}
$result = mysql_query("
INSERT INTO job_spec_contact (contact_info_key, datee, company_name, Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone');
INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure');
");
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['datee'];
echo $row['company_name'];
......
}
mysql_free_result($result);
?>
If you are using mysqli: (Recommended),
$conn = mysqli_connect('localhost','username','password') or die("cannot connect");
mysqli_select_db($conn, 'YourDBName') or die("cannot use database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST['Submit'])){
$datee = $_POST['date'];
$company = $_POST['company'];
$PAddress = $_POST['PAddress'];
$recruiter = $_POST['recruiter'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$company = $_POST['company'];
$agents = $_POST['agents'];
$resumes = $_POST['resumes'];
$structure = $_POST['structure'];
}
$query = "INSERT INTO job_spec_contact (contact_info_key, datee, company_name, Physical_Address, recruitment_person, email, Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone')";
$query .= "INSERT INTO job_company_infor (info_key, company_specialization, no_of_agents, no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
if ($mysqli->multi_query($query)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);//test here your values.
//$datee = $row['datee'];
}
$result->free();
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
Hope this helps.
Note:
Check always POST is present or not by isset. (assume, input name Submit)
Use MySQLi/PDO instead of MySQL to avoid SQL injection.
Debug code by using echo, print_r, var_dump, etc.,
Try to use field names are in same pattern. For ex, Instead of Physical_Address, use physical_address like other fields. Telephone to telephone. datee to job_contact_date, etc.,
Just execute your queries one by one. And DO NOT write error_reporting(0); or the errors won't show. Plus where is your DB ?
$sql1 = "INSERT INTO job_spec_contact (contact_info_key, datee,company_name,Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone')";
$sql2 = "INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
mysqli_query($db,$sql1) or die('error '.$sql1.'<br>'.mysqli_error($db));
mysqli_query($db,$sql2) or die('error '.$sql2.'<br>'.mysqli_error($db));

How to use new format

I have the following query, but this one is old. There should be a new way of writing the following code. Can anyone tell me how i should write this:
$get_test = mysql_query("select test from test_table where id = '1'");
$test = mysql_result($get_test, 0);
Ik would like to write it in: MYSQLI instead of mysql.
Maybe this is what you are looking for:
Mysqli:
<?php
$strSQL = "select test from test_table where id = '1'";
$query = mysqli_query($con, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo $result["test"]."
";
}
?>
PDO:
<?php
$id = 1;
try {
#connection
$conn = new PDO('mysql:host=localhost;dbname=myDB', $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->prepare('SELECT test FROM test_table WHERE id = :id');
$data->execute(array('id' => $id));
while($rows = $data->fetch()) {
print_r($rows);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}?>
You should use PDO:
$db = new PDO("...");
$statement = $db->prepare("select test from test_table where id = :id");
$statement->execute(array(':id' => "test"));
$row = $statement->fetch();

PHP mysql_real_escape_string(); whats the correct method using mysqli?

its a little difficult to explain. I've build the mysql function which works fine and with the depreciation of mysql I will need to change this function to use mysqli rather than the mysql method.
I current have:
$con = mysql_connect("host", "username", "pass");
mysql_select_db("db", $con);
$Username = mysql_real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$Query = mysql_query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'") or die(mysql_error());
$Query_Res = mysql_fetch_array($Query, MYSQL_NUM);
if($Query_Res[0] === '1')
{
//add session
header('Location: newpage.php');
}
else {
echo 'failed login';
}
Now I've applied mysqli to this and it's not returning any data or errors but the function still complies.
$log = new mysqli("host", "user", "pass");
$log->select_db("db");
$Username = $log->real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$qu = $log->query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'");
$res = $qu->fetch_array();
if($res[0] === '1'){
//add session
header('Location: newpage.php');
}
else {
$Error = 'Failed login';
sleep(0.5);
}
echo $res['username'].' hello';
}
But I'm unsure on why this is wrong. I know it's probably a simply answer
Just to have it as an answer:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.prepare.php
e.g.
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
You may check if the connection is establishing before using real_escape_string()
if ($log->connect_errno) {
echo "Failed to connect to MySQL: (".$log->connect_errno.")".$log->connect_error;
}
afaik, there's no problem with $log->real_escape_string($_POST['user']);

Categories