Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Attempting to try and join my table called 'UserCaseMessages' with my other table called 'Comments' using this exact sql command in php:
$sql = "
SELECT UserCaseMessages.DefendantID, Comments.CommentID
FROM UserCaseMessages
INNER JOIN Comments
ON UserCaseMessages.DefendantID = Comments.SenderID
";
$result = $conn->query($sql);
if ($result->num_rows > 0) // ERROR GETS THROWN ON THIS LINE {
}
Here is the connection part to my database (which occurs prior to the query):
$servername = "localhost";
$username = "username";
$password = "password";
// Get the username from the post
$userUsername = $_POST['string'];
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
I get the following error:
PHP Notice: Trying to get property of non-object
I cannot figure out what I am doing wrong here!! Everything is spelled correctly and a checked and checked for any syntax errors and I can't find any, however I am new to this particular method. Please help!
Since you haven't responded to my comments (some 20+ minutes prior to my submitting this), I am posting the following answer.
You didn't choose a database here:
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
so you need to add the database parameter:
$servername = "localhost";
$username = "username";
$password = "password";
$database = "your_DB";
$conn = new mysqli($servername, $username, $password, $database);
Read the manual on connecting with the MySQLi API:
http://php.net/manual/en/function.mysqli-connect.php
Check for errors on the query also:
http://php.net/manual/en/function.mysql-error.php
Plus, make sure the POST array does contain a value. Something in regards to the HTML form you didn't post.
The form's element must contain a matching name attribute:
name="string" and there must be a POST method for <form>.
method="post".
FYI: <form> is the equivalent to <form method="get"> as it defaults to a GET method if POST isn't implied.
Check for errors with error reporting also:
http://php.net/manual/en/function.error-reporting.php
Although, if your form does not have a POST method as I already mentioned, you won't get errors for it, strangely enough.
Sidenote about $userUsername.
That is ambiguous. If you are trying to run a query against that variable, you would need to use a WHERE clause.
I.e.: WHERE column = '$userUsername'
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 months ago.
Improve this question
I'm using a php file to get data from mysql database and display that data in json output, while accessing a certain url address like http://example.com/api/users.php
When I use following code I get json response:
<?php
header("Access-Control-Allow-Origin: *");
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
//Connect to MySQL
$mysql = mysqli_connect($servername, $username, $password, $dbname);
$result_array = array();
$sql = "SELECT username FROM users";
$result = $mysql->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
echo json_encode($result_array);
$mysql->close();
?>
But when trying to get multiple cells from "users" row:
$sql = "SELECT username, avatar, email FROM users";
I get a blank screen in my web browser.
What I'm doing wrong?
If the PHP code you posted is returning a valid json when using single field then the basic code is correct. Now when you try to get multiple fields in the query its showing blank screen. This tells me that possibly your SQL $sql = "SELECT username, avatar, email FROM users"; is throwing error. Try to run this sql statement directly on the database, there can be a mistake in column names.
So if the query fails, your $result_array is empty, and hence the json output is blank.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm just trying to store the integer (with id as id) that is entered by the user through html form, in database of phpmyadmin using php and mysql . I'm new to mysql and php. I'm sure that something wrong with the database connection code of php only or mysql queries. Database name is testdb and the table name is testdbtable.
My code is below.
<?php
if (isset($_POST['id'])) {
$integ = $_POST['id'];
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO testdbtable (id)
VALUES ('$integ')";
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>SAMPLE TEST2</title>
</head>
<body>
<form method="post">
<label >Enter your integer:</label>
<input type="number" id="id" name="id">
<br>
<br>
<button type="submit">Submit</button>
</form>
You're defining the query but never run it.
Try this:
$sql = "INSERT INTO testdbtable (id) VALUES ('$integ')";
$conn->query($sql);
As Paul T. said, move the } to the end of the script. Otherwise, even if condition is false, You will just prevent definig $integ, but still running all the rest of the code.
Also, user Prepared Statements to make it more secure.
if (isset($_POST['id'])) {
$integ = $_POST['id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Use prepared statements to make it more secure
$sql = "INSERT INTO testdbtable (id) VALUES (?)";
// Prepare statement and bind params
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $integ);
// Execute statement
$stmt->execute();
$conn->close();
}
Take a look at Should we ever check for mysqli_connect() errors manually? as #Dharman commented to stop manually error checking.
Before
$conn->close();
you need to run
$conn->query($sql);
This will actually execute the query.
But this is not the end of the story. You have other issues:
Your code is vulnerable to SQL injection attack. Consider changing the line:
$integ = $_POST['id'];
to
$integ = (int)$_POST['id'];
or (better!) learn how to work with prepared statements.
The query will still be invalid. I bet that the datatype of the column "id" in the "testdbtable" is INT and therefore you should not put quotes around its value. So the $sql variable should be:
$sql = "INSERT INTO testdbtable (id) VALUES ($integ)";
And one more thing - move all query-related code inside the if statement. You should not execute the query if the POST variable is not set.
Your <form> tag has no "action" attribute. You should include it so it do an actual post...
I am learning to use MySQL with PHP and while practicing, I tried to create a simple web application using Core PHP and MySQL. It is summarized below:
-It has a pretty simple html page where username(uname) and password(pword) for MySQL are input in a form and are sent by POST method to a PHP script called PHP1.php
-PHP1 makes connection to MySQL. The code is(skipping PHP tags):
//Get input username and password
$username = $_POST['uname'];
$password = $_POST['pword'];
//Server information
$server = "localhost";
//Connect
$conn = new mysqli($server, $username, $password);
//Check success/failure
if ($conn -> connect_error)
{
die("Connection failed".$conn->connect_error);
}
After connecting, PHP1 retrieves information about the databases stored in the respective account and displays radio buttons to select the database and sends the name of the selected database by GET method to another script PHP2.php
-In PHP2.php I want to display the TABLES in the selected database.
However, when control is transferred to PHP2.php, connection to MySQL is terminated. I first tried to include my PHP1.php file in PHP2.php and use the $conn variable but ofcourse it'll try to reconnect to MySQL due to the above mentioned code and at the same time, the first request containing uname and pword is lost resulting in an authentication error.
How can I overcome this problem?
EDIT:
I have seen other questions here but all of them have fixed usernmae/passwords and so the connection script can be placed in a separate file easily. I require to take username and password from the user.
Use Sessions which will persist the session variables across pages:
PHP1
session_start();
$_SESSION['username'] = $username = $_POST['uname'];
$_SESSION['password'] = $password = $_POST['pword'];
$server = "localhost";
$conn = new mysqli($server, $username, $password);
PHP2
session_start();
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$server = "localhost";
$conn = new mysqli($server, $username, $password);
In PHP1 you're going to want to check that the $_POST values are set and in other pages you'll want to check that the $_SESSION variables are set. See isset.
I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.
The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly
Main script:
<?php
include connect.db;
//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";
//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
$stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
$stmt->bind_param("ssss", $type, $username, $password, $email);
$stmt->execute();
$stmt->close();
echo "User Registered";
}
else {
echo "Username, password or email are already used";
}
?>
Connection Script:
<?php
//Identifies the databases details.
//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";
/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
die("Connection failed: " . mysqli_connect_error());
}
?>
edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.
Try to see the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
At the moment, I'm trying to store a value from a MySQL table as a variable in PHP, so running some basic tests to make sure that I can access the variable.
I've managed to store the varaible, which will either be a 1 or a 0 (1 = server is up and running, 0 = server down).
<?php
$servername = "localhost";
$username = "*****";
$password = "*****";
$dbname = "scicomservers";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT nccpm FROM web_servers WHERE time_checked='2016-02-16 11:44:17.212126'";
$nccpm = $conn->query($sql);
if($nccpm==1){
echo("NCCPM Server is running");
}
$conn->close();
?>
When I run this code, it reads in that $nccpm is 1, and it echos the statement, however, I get the error:
Notice: Object of class mysqli_result could not be converted to int in
/Applications/XAMPP/xamppfiles/htdocs/SciCom_admin_servers/files/connect2.php
on line 17
Line 17 being the if statement: "if($nccpm==1){".
I've had a look around on here, and I think this may be because it is trying to print an array of the answers, however it will only ever be one value that I will retrieve. The column of the DB is an int.
I was wondering, what would be a better way of coding this? It clearly isn't the best practice!
Thank you very much.
$sql = "SELECT nccpm FROM web_servers WHERE time_checked='2016-02-16 11:44:17.212126'";
$ncc = $conn->query($sql);
$nccpm = $conn->fetch_array($ncc);
if ($nccpm['nccpm'] == 1)
{
// Rest of script
}
You need to fetch your query or find how many rows are returned