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;
Related
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.
I'm currently working on a project. It's almost done, there's only one big problem. I tested my code all the time with a xamp server on my computer, which worked perfectly fine. the goal is to run it (apache server, mysql database) on my raspberry pi. Now my project is finished, I came figured out the problem why my code doesn't work on my raspberry (at least not as I expected).
I turned on error reporting in PHP and came to this error message:
Notice: Trying to get property of non-object in /var/www/html/test.php on line 41
I use this function for all my SQL queries. Can someone provide a solution so I don't have to rewrite the whole code? Thanks in advance!
PS: this is just a piece of the code (the function where I pull the data out of the database + example of one of my queries)
<?php
// Enable debugging
error_reporting(E_ALL);
ini_set('display_errors', true);
$servername = "localhost";
$username = "root";
$password = "*****"; // I just dont want to give my sql database password its nothing wrong ;)
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
print_r("ok connection");
function sqlquery ($sql, $conn, $naamtabel) {
global $myArray;
global $stateLoop;
$stateLoop = "0";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //line 41 in my code ==> do a while loop to fetch all data to an array
// output data of each row
while($row = $result->fetch_assoc()) {
$myArray[] = $row["$naamtabel"]; //alle data van kolom "tijd" in een array
}
$stateLoop = "1";
}
else { // if there are no results
}
}
$sql1 = "SELECT stopTijd FROM gespeeldeTijd WHERE naam = 'thomas' ORDER BY ID DESC LIMIT 1"; // get data with SQL query
sqlquery($sql1,$conn,"stopTijd");
if ( $stateLoop == "1") {
print_r("ok loop");
$date1 = $myArray["0"];
print_r($date1);
$myArray = [];
$stateLoop == "0";
}
}
?>
It pretty much looks like you have some sql error in your query; check if your field names in your database match those on the raspberry.
Seeing through your code it seems like you are pretty new to programming (which is no bad thing, I was once, too). So I made a few more modifications to your code showing you the prettiness of PHP
use "return" in function sqlquery instead of globals
check for errors after executing the code
use only one variable to check if data was loaded
I commented everything I changed
<?php
// Enable debugging
error_reporting(E_ALL);
ini_set('display_errors', true);
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "test";
// Your function with some modifications
function sqlquery($sql, $conn, $naamtabel) {
$result = $conn->query($sql);
// Check for errors after execution
if(!$result)
die('mysqli error: '. htmlentities(mysqli_error($con)));
// If we have no data, we simply return an empty array
if($result->num_rows == 0)
return array();
// This is a variable we store the data we processed in
// We will return it at the end of our function
$myArray = null;
// Read all field data and store it $myArray
while($row = $result->fetch_assoc())
$myArray[] = $row[$naamtabel]; // if you use "$naamtabel" here, PHP first needs to interpret the string (= slower)
return $myArray;
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Because we use "die" above we don't need an "else"-clause
print_r("ok connection");
$sql = "SELECT `stopTijd` FROM `gespeeldeTijd` WHERE `naam` = 'thomas' ORDER BY `ID` DESC LIMIT 1";
$data = sqlquery($sql, $conn, "stopTijd");
// $data will contain $myArray (see "return $myArray" in function sqlquery)
// Instead checking for $stateLoop being "1" we check if $data contains any values
// If so, we fetched some data
if(sizeof($data) >= 1) {
print_r("ok loop");
$date1 = $data[0]; // No "0", because we are trying to get index 0
print_r($date1);
$data = array(); // Are you sure this is nessecary?
} else {
echo 'No data returned from query!';
}
?>
Note: code tipped on my smartphone -> untested!
If you don't want to adapt the code I wrote, the important part for this question is:
if(!$result)
die('mysqli error: '. htmlentities(mysqli_error($con)));
Your error Notice: Trying to get property of non-object means "you are trying to get num_rows from $result, but $result is not an object, so it can't contain this property".
So to figure out why $result is not an object, you need to get the error from $conn->query - my code above probably won't fix your error, but it will display you one you can work with (+ it's too long for a comment)
If you have a more detailed error message and you can't solve it on your own, feel free to comment; I will update my answer!
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';
}
I have written a small script that issues a series of commands via write() to a linux machine, with a 5 second sleep() between each one. The exact same commands work when entered manually but despite being connected successfully, do not seem to work when used from a PHP script.
As this is the case, I am curious if using read() is absolutely necessary prior to issuing a write() command?
<?php
include('Net/SSH2.php');
$serverhostname = "IP_HERE";
$ssh_username = "root";
$ssh_password = "PASS_HERE";
// Establish new SSH2 Connection
$connection = new Net_SSH2($serverhostname, 22);
if($connection->login($ssh_username, $ssh_password))
{
echo "LOGGED IN! </br>";
sleep(5);
$result = $connection->write('en PASS_HERE\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('configure terminal\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('interface ve 110\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('port-name Test_Brett\r\n');
echo "RESULT: " . $result . " </br>";
}
else
{
echo "SSH Connection Failed. Check that the remote host is online and accepting connections!";
}
?>
UPDATE
$result = $connection->write('en PASS_HERE\n');
$result = $connection->write('configure terminal\n');
$result = $connection->write('interface ve 110\n');
$result = $connection->write('port-name Test_Brett\n');
$connection->setTimeout(5);
echo $connection->read();
I just did this:
$connection->write("ls -la\n");
$connection->write("pwd\n");
$connection->setTimeout(5);
echo $connection->read();
And it seemed to perform the commands just fine without a read() between the two write()'s. But it could be that a read() has to be done, even if just once, at the end.
What I'd do if I were you is, instead of doing sleep(5) do $connection->setTimeout(5); $connection->read();. You can throw away the return value of read(). If you knew what to expect back you could just do $connection->read('pattern'), which would be faster, but if you don't, I'd do the $connection->setTimeout(5); route just to be on the safe side.
I have made a program using PHP and trying to store data into Local Server Xampp, but whenever i run my php script using this url:
http://127.0.0.1/test.php
Getting error message: {"StatusID":"0","Error":"Cannot save data!"}
Please someone help me in this how can i make it useful for me, please check below PHP Script:
<?php
$objConnect = mysql_connect("localhost","root","");
mysql_error($ObjConnect);
$objDB = mysql_select_db("registration_login");
mysql_error($ObjDB);
$strUsername = $_POST["sUsername"];
$strPassword = $_POST["sPassword"];
$strName = $_POST["sName"];
$strEmail = $_POST["sEmail"];
$strTel = $_POST["sTel"];
/*** Insert ***/
$strSQL = "INSERT INTO member (Username,Password,Name,Email,Tel)
VALUES (
'".$strUsername."',
'".$strPassword."',
'".$strName."',
'".$strEmail."',
'".$strTel."'
)
";
$objQuery = mysql_query($strSQL);
mysql_error($ObjQuery);
if(!$objQuery)
{
$arr["Status"] = "0";
$arr["Message"] = "Cannot Save Data!";
echo json_encode($arr);
exit();
}
else
{
$arr["Status"] = "1";
$arr["Message"] = "Register Successfully!";
echo json_encode($arr);
exit();
}
mysql_close($objConnect);
?>
Note: I have created registration_login database and member table under this DB..
Why don't you return the error reported by mysql or log it somewhere?
$objConnect = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
You forgot to check the return the return value to see if this was successful - if it failed, the reason is in mysql_error()
$objDB = mysql_select_db(DB_DATABASE);
You forgot to check the return the return value to see if this was successful - if it failed, the reason is in mysql_error()
$objQuery = mysql_query($strSQL);
At least this time you check the return value - but you don't check what the error was.
BTW your script is wide open to SQL injection.
Convert mysql_* to PDO
What has that got to do with your post?