My connection to mysql works but no any query [duplicate] - php

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
I'm having a bit of a weird problem.
I'm trying to read data of my database, the connection works but the instruction doesn't.
I try with code that should work, query("show tables"); but this also doesn't show anything.
Application is another php in which I make the connection and configuration with the database.
use Aplication as App;
class Company {
public static function login($username, $password) {
$app = App::getSingleton();
$conn = $app->conexionBd();
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$query = sprintf("SELECT * FROM company E WHERE E.Name= %s", $conn->real_escape_string($username));
$rs = $conn->query($query);
if ($rs)
{
$row = $rs->fetch_assoc();
$c = new Company($row['id'], $row['Name'],$row['Password']);
$rs->free();
return $c;
}
return false;
}
}
What is wrong?
Thanks in advance!

Best way to troubleshoot such problems is to print the query and run on mysql command prompt.
E.Name= %s should be changed to E.Name= '%s' as strings should be enclosed by quotes.

Related

PHP SQL Server Connection working or not working [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
$serverName = 'servername';
$uid = 'username';
$pwd = 'password';
$conn = new mysqli($serverName, $uid, $pwd );
if (!$conn) {
echo "Connection failed: " ;
}
else
{
echo "Connected successfully";
}
This is my code. It gets connected to the database. I just want to confirm the code is right, because when i try doing this
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
it throws me connection failed error.
So, is my code connected to the server or not? because when i run a query it does not show me anything.
Code for the query:
$sql = "SELECT max([line_nbr]) FROM [dbo].[so_audit]";
$res = $conn->query($sql);
var_dump($res);
please advise
you are not trying to connect to sql server u should use sqlsrv_connect instead of mysqli
so u need to specify the server name and an array containin connection info for that your code should look like this :
$srv ="servername"
$info=array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $srv, $info);
if (!$conn) {
echo "Connection failed: " ;
}
else
{
echo "Connected successfully";
}

PHP error from bind param [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I'm new to PHP but here's my code, and I'm getting :
Fatal error: Uncaught Error: Call to a member function bindParam() on boolean
I have tested and test, not sure what is going wrong, some pointers would really help to move on - thanks in advance.
$url_slot = parse_url($str);
$urlArray = explode('/',$url_slot['path']);
$passid = $urlArray['11']; // serial no
$deviceId = $urlArray['8'];
$passtype = $urlArray['10'];
$servername = "host";
$username = "user";
$password = "******";
$dbname = "db";
try {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO Registrations (device_id, pass_id, pass_type) VALUES
(:device_id,:pass_id,:pass_type,:created,:modified)");
$stmt->bindParam(':device_id',$device_id);
$stmt->bindParam(':pass_id',$pass_id);
$stmt->bindParam(':pass_type',$pass_type);
$device_id = $deviceId;
$pass_id = $passid;
$pass_type = $passtype;
$stmt->execute();
$conn = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
try {
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO Devices (push_token) VALUES
(:push_token)");
$stmt->bindParam(':push_token',$push_token);
$push_token = $content['pushToken'];
$stmt->execute();
$conn = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Any help would be great.
Whenever you get a Fatal error for sending the wrong type to a function, print the arguments you are trying to pass on the guilty line.
Whenever the wrong type in question is a boolean, check if you wrote tests for every function return that could hurt your program if the function had failed, because a variable that contains a boolean when it shouldn't usually does because the function that gave you that value failed and returned false.
In your case, it's even more simple : The error doesn't tell you that you try to pass a boolean to a function that awaits another type, it tells you that you try to call the method bind_param(), which means that you treat a boolean as an object.
$stmt->bindParam(':device_id',$device_id);
Therefore, it is $stmt which is empty.
$stmt = $conn->prepare("INSERT INTO Registrations (device_id, pass_id, pass_type) VALUES (:device_id,:pass_id,:pass_type,:created,:modified)");
The function that returns you the value you assign to $stmt being that one, I advise you to test if $stmt is different from false right after setting it, and to print the error type and message from $conn if it isn't.
In addition to that, I get the feeling that you aren't yet accustomed to work with API, you seem to lack some experience and are also trying to use PDO exceptions while working with MySQLi. Maybe you should spend some time reading their respective docmuentations.
Stack Overflow is also filled with various questions and docs regarding both.

Using include/require to connect database [duplicate]

This question already has answers here:
Call to a member function prepare() on a non-object PHP Help [duplicate]
(8 answers)
Closed 6 years ago.
I have a following code
//dsn.php
//Object Oriented way
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
//check connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error) {
die("could not connect:".$conn->connect_error);
}
//index.php
include 'dsn.php';
function a() {
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
$sql = "sql command";
$result = $conn->query($sql);
//not working
$conn->close();
}
This will display warning and notice that says:
Warning: mysqli::query(): Couldn't fetch mysqli
Notice: Trying to get property of non-object
Warning: mysqli::close(): Couldn't fetch mysqli
However this one works:
include 'dsn.php';
function a() {
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
include $dsn.php
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
How do I use just one include file for DSN and use repeatedly on other functions?
EDIT
sorry I forgot to mention
function a($conn) {}
function b($conn) {}
I passed the variable $conn but it still displays the warning and notice I mentioned above
When you include a file, you can imagine that in the background it is just copy-pasting that code into the current document.
There are 2 problems with your code...
The $conn variable is not in scope inside function a or b.
Even if it was in scope and accessible, you are closing the connection after each query. A better way to do it is to open the connection, run all queries and close the connection when it is no longer needed.
The second piece of code you gave works because it is creating a new variable $conn inside of b(), but this is not ideal as it will create a new database connection every time you execute that function.
Something like this may suit your needs:
include 'dsn.php';
function a($conn) {
$sql = "sql command";
$result = $conn->query($sql);
return $result;
}
function b($conn) {
$sql = "sql command";
$result = $conn->query($sql);
return $result;
}
$aResult = a($conn);
$bResult = b($conn);
$conn->close();
Notice that we are only including 'dsn.php' once, and then passing around that existing connection to the functions that need it.
This is very simple. On page load, the connection file is included which makes $conn the connection object available to the remaining codes. The $conn is used by the functiona() and it is then closed at the end of the function. $conn->close(); destroys the database connection object means, $conn is no more object hence it should not be treated as object. But the Function b() is treatong it as database connection object and resulting into error.
But if you again include the connection file, inside the function b() then $conn becomes available to the function as local object. And works as it should.
Do not close the $conn() on the any function till you are dealing with DB.
function a() {
incDbConnectionFile();
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
incDbConnectionFile();
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function incDbConnectionFile() {
include 'dsn.php';
}

Trying to insert data into a database using PHP / Mysqli

I'm trying to execute an Insert query to write data into a Database. I'm using Mysqli and PHP.
The code looks OK for me. However, every time I go to the webpage to check if the form works, the query gets executed an a new row is created in the DB (empty).
I'm pretty sure there is something wrong with the last if statement. Could you advise?
BTW, the snippet is only for the PHP to execute the sql query, since the form is working just fine.
Thanks!
$servername = "localhost";
$username = "root";
$password = "mysqlpassword";
$dbname = "bowieDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$album = $_POST['album'];
$relyear = $_POST['relyear'];
$label = $_POST['label'];
$chart = $_POST['chart'];
$track1 = $_POST['track1'];
$track2 = $_POST['track2'];
$track3 = $_POST['track3'];
$track4 = $_POST['track4'];
$track5 = $_POST['track5'];
$sql = "INSERT INTO Albums (album, relyear, label, chart, track1, track2, track3, track4, track5)
VALUES ('$album', '$relyear', '$label', '$chart', '$track1', '$track2', '$track3', '$track4', '$track5')";
$result = mysqli_query($conn, $sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
You are mixing Procedural and Object Orientated SQL interactions.
This is Procedural:
$result = mysqli_query($conn, $sql);
This is Object Orientated:
$conn->query($sql)
You can not use both with the same connection details, you should do one or the other throughout your code. The best one to use is Object Orientated approach, so rework the Procedural code to:
$result = $conn->query($sql);
if ($result) {
...
So actually you can simply remove the line starting $result = ... and let the IF statement query you already have handle itself.
Other notes:
Use MySQL error feedback such as checking if(!empty($conn->error)){print $conn->error;} after SQL statements. See example code below...
Use the following PHP error feedback too, set at the very top of your PHP page:
...
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
you need to read up and be aware of SQL injection that can destory your database should someone POST data that also happens to be MySQL commands such as DROP.
Code for Comment:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
//run SQL query you already have coded and assume
// that the form has been filled in.
$result = $conn->query($sql);
if ($result) {
//all ok
}
if(!empty($conn->error)) {
print "SQL Error: ".$conn->error;
}
}
use
1. if(isset($_POST['Submit'])){//your code here }
and
2. if($result){...
if you are using procedural method

Cron Jobs calling a PHP script with variables not working [duplicate]

This question already has answers here:
Pass a variable to a PHP script running from the command line
(14 answers)
Closed 3 years ago.
Hello i have tryed a few of the other posting fixes to see what i am doing wrong but its still not pulling the variable passed in my cron job string
php -q public_html/conquest/update_power_server.php method=Password
That is my Cron Job String and this is the script its calling.
$mymethod = $_SERVER['argv'];
$method = $mymethod[1];
$con=mysqli_connect("localhost", $user_name, $password, $database_name);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo $method;
if($method == $scpassword)
{
$result = mysqli_query($con,"SELECT * FROM `$table_name` WHERE energy < 30");
while($row = mysqli_fetch_array($result))
{
$uuid = $row['uuid'];
$newenergy = $row['energy'] + 1;
mysqli_query($con,"UPDATE `$table_name` SET energy = '$newenergy' WHERE uuid = '$uuid'");
}
mysqli_close($con);
exit;
}else{
echo ("Access Denied!!!");
exit;
}
?>
Its calling the script but cant figger out how to get the variable to pass so i can use it any help pointing me in the right direction or helping me fix would be helpful thank you.
This is how I fixed it:
$mymethod = $_SERVER['argv'];
$arrmethod = $mymethod[1];
parse_str($arrmethod);
echo $method;

Categories