Get a data in a database? - php

I would like to get the registered IP of a user in my database.
I use this method :
$securityRes=mysql_query("SELECT * FROM security WHERE userName=".$userRow['name']);
$securityRow=mysql_fetch_array($securityRes);
But it return me nothing, when I use this code :
echo $securityRow['IP']
I'm blocked on it since like 1 hours, and Google seems to don't want to be my friend today :/
So I ask help here, hoping I will get some.
Thank you in advance; cordially, Matt.
PS - Here is my database | my table "security" :

First of all use mysqli_* instead of mysql_*. And the issue is here:
"SELECT * FROM security WHERE userName=".$userRow['name'];
name is always a string, and for string comparison you have to bind the value in single quotes like:
"SELECT * FROM security WHERE userName='".$userRow['name']."'";

You should try debugging here.
$securityRes = mysql_query("SELECT * FROM security WHERE userName=".$userRow['name']) or die(mysql_error());
$securityRow = mysql_fetch_array($securityRes);
echo "<pre>";
print_r($securityRow); // Check your result

Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
1) In your code you need string to be enclosed by single quotes.
2) Try to use prepared statement or PDO like this
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
$stmt = $conn->prepare("SELECT * FROM security WHERE userName=?");
$stmt->bind_param('s',$userRow['name']);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$get_result =$stmt->get_result();
$row_count= $get_result->num_rows;
if($row_count>0)
{
print_r($get_result->fetch_assoc());
}

Related

Php not updating table info but query works when executed alone, so do post method and mysqli_connect

<?php
$host_name = '***';
$database = '***';
$user_name = '***';
$password = '***';
$link = mysqli_connect($host_name, $user_name, $password, $database);
$con = $_POST['User_ID'];
echo "Se ha ascendido al usuario $con";
$meta= 'a:1:{s:13:"administrator";b:1;}';
$consulta = 'UPDATE ***usermeta
SET
meta_value = $meta
WHERE
User_ID=$con and meta_key = "***capabilities"';
mysqli_query($link, $consulta);
echo "<br><br><br><a href='***'>Volver</a>";
In this code im trying to update an specific column from a table but it just wont work, it appears like it is working but when i go into phpmyadmin the data wont update, here is some info to keep in mind:
mysqli_connect works
query works when i execute it on phpmyadmin
i can do other queries (select) that works
data is correctly received by POST method
those " from variable $meta have to stay
I honestly dont have any idea of what is causing the code to just not work, not a single syntax error displayed or anything else. At first i thought it had something to do with the quote marks but now i dismissed that posibility.
Any help?
There's a catalog of issues here.
Your update statement is wrapped in single quotes - so your variables will not be substituted.
You've used double quotes as a delimiters for strings inside the query - that's not supported by SQL - they should be single quotes.
Table names cannot cannot contain asterisk characters.
That you are not seeing "a single syntax error" is a major issue - the DBMS will be screaming for help when it sees this.
Embedding composite data (json) in a scalar value is just asking for trouble.
Your code is vulnerable to SQL injection.
Whenever your thread of execution leaves PHP (in your code, when you call mysqli_conect() and mysqli_query()) you should be explicitly checking the result of the operation.
For one, you should have some kind of error handling so you know what the problem is. Secondly, you're calling mysqli_query directly instead of using it as a method from your already instantiated class $link.
Also, you really should be using back-ticks for column names and single quotes for column values.
Lastly, you need to escape certain special characters using mysqli_real_escape_string. Alternatively, you could use prepared statements, but I'll keep it simple. Instead of prepared statements, you can use PHP's sprintf function.
<?php
$host_name = '***';
$database = '***';
$user_name = '***';
$password = '***';
$link = mysqli_connect($host_name, $user_name, $password, $database);
$con = $_POST['User_ID'];
echo "Se ha ascendido al usuario $con";
$meta= 'a:1:{s:13:"administrator";b:1;}';
$consulta = "UPDATE `usermeta`
SET
`meta_value` = '%s'
WHERE
`User_ID`='%s' and `meta_key` = 'capabilities'";
$consulta = sprintf(
$consulta,
esc($meta),
esc($con)
);
$link->query($consulta);
echo "<br><br><br><a href='***'>Volver</a>";
function esc($v)
{
global $link;
return $link->real_escape_string($v);
}
?>
Not sure what the asterisks are in the table name, but they shouldn't be there. Also, note that I created a function for handling escaping for brevity.
EDIT:
For error handling, you should check $link->error.
Example:
<?php
$dbError = $link->error ?? null;
if (!empty($dbError))
{
die("A database error occurred: {$dbError}!");
}
?>

query doesn't working using php

I am new in Php and MYsql,
I am trying to create a simple query using which contain a variable using php.
however I think I am not writing the querty correctly with the variable since the result of this query is 0.
would be happy for assistance here is my code:
<?php
$phone = $_GET['phone'];
echo $phone;
$query = "SELECT * FROM `APPUsers` WHERE `Phone` LIKE "."'".$phone."' ";
echo $query;
$result = mysqli_query($mysqli, $query);
echo mysqli_num_rows($result);
?>
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = $conn->query($sql);
Above there is a fast solution , but it is not safe ,
because is vulnerable to injection ...
Below let's see how to do it and why to do it in this way
It is a good practice to store sensible information in a separate file
out of the document root , it means will be not accesible from the web .
So let's create a file configDB.ini for example and put in db informations
servername = something;
username = something;
password = something;
dbname = something;
Once did it we can create a script called dbconn.php and import the file with credentials ,
in this way there is an abstraction between credentials and connection .
in dbconn.php :
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
We can even improve the code connecting to db only once and use the same connection all the time we need query .
function db_connect() {
// static will not connect more than once
static $conn;
if(!isset($conn)) {
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
return $conn;
}
...
$conn = db_connect();
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = mysqli_query($conn,$sql);
In the end let's say something about mysqli_query
Reasons why you should use MySQLi extension instead of the MySQL extension are many:
from PHP 5.5.0 mysql is deprecated and was introduced mysqli
Why choose mysqli (strenghts)
object oriented
prepared statements
many features
no injection
Do you connect to the database?
The apostrophes around APPUsers and Phone might not be the right ones, as they are not the single apostrophes but some weird squiggly ones.
Try this :
$query = "SELECT * FROM 'APPUsers' WHERE 'Phone' LIKE '".$phone."' ";

Migrating to PHP7.x, Deprecated functions

So here's the problem, the script I purchase is written on PHP 5.x, and I'm using xampp with PHP7.x installed for development. Now I want to migrate my script to PHP7.x. Now I know this was asked a million times already but do you mind if you could take a look at my code and give your thoughts about it, or simply share your knowledge. I would deeply appreciate it.
Here is the code for my config.php
<?php
// mySQL information
$server = 'localhost'; // MySql server
$username = 'admin'; // MySql Username
$password = 'admin' ; // MySql Password
$database = 'arcade'; // MySql Database
// The following should not be edited
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$con = mysql_connect($server, $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
// Get settings
if (!isset($install)) {
$sql = mysql_query("SELECT * FROM ava_settings");
while ($get_setting = mysql_fetch_array($sql)) {
$setting[$get_setting['name']] = $get_setting['value'];
}
}
?>
The deprecated functions are:
mysql_connect()
mysql_error()
mysql_fetch_array()
mysql_query()
mysql_select_db()
Now, I don't want to use the PDO approach, I want to use mysqli instead. Am I suppose to just replace the mysql_* into mysqli_*? So it will become like these? I don't want to hide/surpress the deprecate warnings.
mysqli_connect()
mysqli_error()
mysqli_fetch_array()
mysqli_query()
mysqli_select_db()
I just offer you that migrate to PDO driver. Because every update you may see a lot of deprecation errors.
But if you can not do it the first thing to do would probably be to replace every mysql_* function call with its equivalent mysqli_*, at least if you are willing to use the procedural API -- which would be the easier way, considering you already have some code based on the MySQL API, which is a procedural one.
Note that, for some functions, you may need to check the parameters carefully: Maybe there are some differences here and there -- but not that many, I'd say: both mysql and mysqli are based on the same library (libmysql ; at least for PHP <= 5.2)
Look at difference between mysqli and mysql:
$mysqli = mysqli_connect("example.com", "user", "password", "database");
$res = mysqli_query($mysqli, "SELECT ...");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];
$mysql = mysql_connect("example.com", "user", "password");
mysql_select_db("test");
$res = mysql_query("SELECT ...", $mysql);
$row = mysql_fetch_assoc($res);
echo $row['_msg'];

Object returned on mysql_num_rows() function

I am working on a login script with prepared statements in PHP procedural mysqli syntax. Here is my current code:
<?php
include "/ssincludes/functions.php";
$host = HOST;
$username = USER;
$password = PASSWORD;
$db_name = DATABASE;
$table = TABLEU;
//These includes and constants are fine I checked them all
$con = mysqli_connect($host, $username, $password, $db_name);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$myusername='test';
$mypassword='password1';
$sql="SELECT * FROM $table WHERE user_name=? and password=?";
$result=mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($result, 'ss', $myusername, $mypassword);
mysqli_execute($result);
mysqli_stmt_fetch($result);
$row_cnt = mysqli_num_rows($result);
echo $row_cnt;
?>
The error returned is: Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, object given
I thought I took out all instances of OO PHP in my script? Also I understand that this may mean my query is incorrect so I ran it on MySQL in the database and all seems to be fine there:
So I am lost as to what the problem could be. I read many similar posts (maybe I'm missing one that is exactly similar to mine) and none seem to handle the problem. I appreciate your time and help.
P.S. I understand the security issues with plain text passwords and using "password1". I plan to use better security practices as I build this but I just want to get prepared statements down first.
You should use
mysqli_stmt_execute
mysqli_stmt_num_rows
Instead of the mysqli_execute and mysqli_num_rows.

PHP/MySQL - Cannot get PHP script to put data into MySQL Database

I've spent most of the day trying to get data from a form into a MySQL Database, everything I have tried so far has not worked, can anyone figure out what is wrong? The database is connecting fine, it just cannot add any data into the mysql database (current errors are at the bottom)
EDIT: Updated Code Below (Still not working!)
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "report"; // Database name
$tbl_name = "tbl_nonconformance"; // Table name
// Connect to server and select database.
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
echo "Database Connected ";
$name = $_POST['name'];
$email = $_POST['email'];
$supplier = $_POST['supplier'];
$PONum = $_POST['PONum'];
$Part = $_POST['Part'];
$Serial = $_POST['Serial'];
$tsf = $_POST['tsf'];
$Quantity = $_POST['Quantity'];
$probclass = $_POST['probclass'];
$desc = $_POST['desc'];
$sql="INSERT INTO tbl_nonconformance (sno, Date, Name, Email, Supplier, PONum, Part, Serial, TSF, Quantity, probclass, desc)
VALUES
('$sno', '$date', '$name', '$email', '$supplier', '$PONum', '$Part', '$Serial', '$TSF', '$Quantity', '$probclass', '$desc')";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
header('Location: ../thankyou.php');
}
else {
echo "ERROR";
}
// close mysql
mysql_close();
?>
First you should change
mysql_connect("$host", "$username", "$password") or die("cannot connect");
to:
$con = mysql_connect($host, $username, $password) or die("cannot connect");
You are calling $con but you never defined it. You want to save your MySQL connection (con) as $con for what you are trying to do here.
You should also really consider upgrading to MySQLi as MySQL is deprecated from PHP and will likely be removed from future versions. Here's a resource to get you started. http://www.php.net/manual/en/book.mysqli.php
Edit July 9 2014: You updated your code, and I do not recall what your original code was. Still, if it's not "working", it's best to describe how it's not working. After you call $result, do this:
if( !$result || !mysql_affected_rows() )
die( mysql_error() );
header('Location: ../thankyou.php'); //this will only occur if there are no SQL errors and the result actually inserted something
mysql_close();
echo "We couldn't forward you automatically. Click here to proceed {insert HTML/JS here}";
This will return the MySQL error message which will help you in your debugging.
You got your argument parsing wrong.
$name = mysql_real_escape_string($con, $_POST['name']);
$con is not defined first of all.
Secondly you are trying to escape $_POST['name'].
mysql_real_escape_string expects 2 arguments, 1st one is mandatory and second one is optional. First argument is the string you want to escape, the second specifies a mysql connection (optional as you may have one open already).
So your statement needs to look like
$name = mysql_real_escape_string($_POST['name']);
Perhaps $con is your mysql connection? Which if it is the case you may want to
$con = mysql_connect ........ and so on
you're using un-secure depreciating methods too. You should research PDO object. It separates variables from your query so they aren't sent at the same time. It also cleans code considerably. I see a few problem areas in his code... You pass in $sno, $date, but they don't exist in your code. $tsf has a different case in instantiation then what you're using in your query. You're using single quotes which can't interpolate data (place values where variable names are). Double quotes do that...
hmmm...
check this out.
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_port = "3306" // Mysql port
$db_name = "report"; // Database name
$dsn = "mysql:dbhost=$host;dbport=$db_port;dbname=$db_name";
//add sno variable declaration here.
$name = $_POST['name'];
$email = $_POST['email'];
$supplier = $_POST['supplier'];
$PONum = $_POST['PONum'];
$Part = $_POST['Part'];
$Serial = $_POST['Serial'];
$TSF = $_POST['tsf'];
$Quantity = $_POST['Quantity'];
$probclass = $_POST['probclass'];
$desc = $_POST['desc'];
$date = date('d-m-Y');
// Connect to server and select database.
$dbConnect = new PDO($dsn, $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sqlStatement = $dbConnect->prepare("INSERT INTO tbl_nonconformance (sno, Date, Name, Email, Supplier, PONum, Part, Serial, TSF, Quantity, probclass, desc)VALUES('?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')");
try{
$sqlStatement->execute(array($sno, $date, $name, $email, $supplier, $PONum, $Part, $Serial, $TSF, $Quantity, $probclass, $desc));
header('Location: ../thankyou.php');
}catch(\PDOException $e){
echo 'Error: Could not connect to db.';
}
?>
PDO object is really easy. create $dbConnect = new PDO(). You see the arguments there. dsn, username, password. The last argument is just an associative array setting PDO's error mode with constants. This allows us to use the try catch block to do error handling. IF PDO can't connect we get the catch block to fire...otherwise the try block which is where our data is sent to the db... You see we have a variable called $sqlStatement.. this is made through $dbConnect->prepare(). This function takes the statement... notice variables are excluded for question marks. Inside the try block we call execute from the statement...this takes and array of values that will replace the question marks in order.
remember to create sno variable. I added date for you. also be sure all cases and spellings are right. One letter in your query string, whether spelled wrong, or even just cased wrong will cause a failure.
let me know if there's any errors or questions. jeremybenson11#gmail.com

Categories