I am trying to make a messenger using PHP and SQL
This is my code
<form action="send_post.php" method="post">
<h3>Name:</h3>
<input type="text" name="name">
<h3>Message:</h3>
<input type="text" name="message">
<input type="submit">
</form>
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, message FROM chat";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
while(1){
ob_start();
echo "" . $row["name"]. " - " . $row["message"]. "<br>";
sleep(10);
echo "" . $row["name"]. " - " . $row["message"]. "<br>";
ob_end_clean();
}
}
}
$conn->close();
?>
However this does not work, is there any reason for this?
The problems started once I added the infinite while loop to refresh the messages.
PHP works serversided, which means that the client(guest) requests a page that the server then "compiles" to then send to the client as a clientsided language such as HTML. If the PHP code never reaches an end/stop the client browser is going to think the server stopped responding and give an error.
To achieve what you are trying to do you might want to look into something like JQuery AJAX which allows for the client to fetch data from the server seperatly from the main request. That way you can have one file showing only the messages and request that file on a timer, while having the form as usual page load. You can however also make the form dynamic using JQuery AJAX
UPDATE You can look at this blogpost to get an idea of what I'm talking about.
Related
I've looked all over here. Please be patient as I am new to php and mysql.
I got WAMPP installed & seems to be working OK. I created a simple "test" database from phpMyAdmin and "firsttable" in that. I can do a simple connect using example from w3schools, but trying to select & display data I entered only throws back errors.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Connect
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT reference, firstname, lastname, room FROM firsttable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["reference"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "room:" . $row["room"]. "<br>";
}
} else {
echo "0 results";
}
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
First off, I get a parse error on line 17. The one that reads:
if ($result->num_rows > 0) {
The error says: Trying to get property of non-object.
I tried wrapping the whole php code in tags and saving it as html, but then it appeared that no row data was ever found.
I am able to use very simple code that connects successfully. I can confirm the database is in there, so is the table, and the contents I added to it.
Please, what am I doing wrong?
You need to specify the database when you connect:
$database = 'test';
$conn = mysqli_connect($servername, $username, $password, $database);
where $database is the name of your database (test in this case). MySQL doesn't know which database your table resides in without you telling it.
In addition, you should always include error checking for your database connection (you have two of these, you don't need the last one) as well as any queries. Sans this, you can check your error logs for more information when something fails.
I have been trying to get this to work for some hours. I have researched many threads on here trying to see if I could find the problem with my code. I am new to PHP and I keep getting a Internal Server error, but I cant seem to track it down. I have tried all sorts of methods suggested online to get this to work with no luck. Its a basic user signup form in HTML, in a PHP file.(I was going to do both html and php on the same file but could not get that to work) The idea is to have the form submit to my MYSQL database to a customer table. If any of you could shed some light on what I am doing wrong or point me in the right direction, it would be much appreciated. Thanks in advance.
HTML
<form id="signupField" action="register.php" method="post">
First Name:<br>
<input type="text" name="FN" size="auto"/><br>
Last Name:<br>
<input type="text" name="LN" size="auto"/><br>
Street Address:<br>
<input type="text" name="SA" size="auto"/><br>
City:<br>
<input type="text" name="City" size="auto"/><br>
State:<br>
<input type="text" name="ST" size="auto"/><br>
Zip:<br>
<input type="text" name="Zip" size="auto"/><br>
Email Address:<br>
<input type="text" name="Email" size="auto"/><br>
Password:<br>
<input type="text" name="Password" size="auto"/><br>
<input type="submit" value="submit" name="submit"/>
</form>
Referenced PHP:
<?php
$hostname = "localhost";
$username = "serviceaccount";
$password = "password";
$dbname = "nameofdb";
$conn = new mysqli($hostname,$username,$password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
<?php
$FName=$_POST["FN"];
$LName=$_POST["LN"];
$SA=$_POST["SA"];
$City=$_POST["City"];
$State=$_POST["ST"];
$Zip=$_POST["Zip"];
$Email=$_POST["Email"];
$Password=$_POST["Password"];
if (isset($_POST["submit"])) {
$sql = "INSERT INTO Customers(FName,LName,StreetAddress,City,State,Zip,Email,Password) VALUES('$_POST["FN"]','$_POST["LN"]','$_POST["SA"]','$_POST["City"]','$_POST["ST"]','$_POST["Zip"]','$_POST["Email"]','$_POST["Password"]')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
}
?>
EDIT After finding this error: Connection failed: Unknown MySQL server host 'localhost:3306' (0) I was able to solve the connection issue to the database. Now when I put in the rest of the PHP back in I get a 500 Error still. It definitely narrows down where the issue is though!
EDIT I want to thank you all for you help on here. The main issue was the SQL connection. After I got that taken care of, I found that I had an extra bracket in place which was the cause for the other internal error I was receiving.
First, the "basic check" question: the html with the form and register.php are in the same directory, right? Not includes, requires, etc
If you have access to the apache error_log, check it out first to see the error message you're getting. If you can't understand it, post it here to help you.
If you don't have acccess to the file, first we need to find where are you getting the mistake. As an idea, start with this in register.php...
<?php
$hostname = "localhost";
$username = "serviceaccount";
$password = "password";
$dbname = "nameofdb";
$conn = new mysqli($hostname,$username,$password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Got to http://[yourdirectory]/register.php DIRECTLY and see what you get. Then start adding the rest step by step and let us know when you get the mistake.
Other think to check is the database NULL variables configuration. All the columns allow null values? Are you filling all form fields or are you leaving any field empty?
Replace your register.php code with following.
<?php
$hostname = "localhost";
$username = "serviceaccount";
$password = "password";
$dbname = "nameofdb";
$conn = new mysqli($hostname,$username,$password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
if it prints that connection failed; then you have to check your code for connecting to database.
Use isset($_POST["FN"]) .. etc for all post variables and try to use variables $FName , $LName etc. in your insert query instead of direct $_POST variables.
e.g.
$FName = '';
if(isset($_POST["FN"]) && $_POST["FN"] !=''){
$FName = $_POST["FN"];
}
Also check whether connection is opening or failing.
before insert any new field into your db use
mysql_real_escape_string
check for empty params before insert these to db
use the following to turn all error reporting on for MySQLi
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
You should use your variables that you assigned for your post fields instead of the $_POST-objects and make sure you sanitize all user inputs.
You could try replacing your $sql-string with the following:
$sql = "INSERT INTO Customers(FName,LName,StreetAddress,City,State,Zip,Email,Password) VALUES('$FName','$LName','$SA','$City','$State','$Zip','$Email','$Password')";
I'm not sure if this is a duplicate question due to the fact that I'm not even sure how to properly form it (That's why the title of this question makes no real sense). I am beginning to learn PHP so I can utilize SQL databases in my webpages.
My question is, how would I be able to make it so a user types in a password into an input box, which is then used by a PHP script as the password to a MySQL login to display the contents of a table in an HTML table? Now, I have most of this figured out, the only problem is displaying the table on the same page which the password is entered and the submit button is hit. Would I need to use AJAX? Because I don't know the first thing about it. Here is what I have so far:
Index.php:
<DOCTYPE! html>
<html>
<head>
<title>Guy's Random Project</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="scripts.js"></script>
</head>
<body>
<div>
<form action="" method="POST">
<font size="4">Password: </font><input type="text" id="pass" name="pass"/><br>
<input class="buttonGreen" type="submit" value="Submit" id="1" onMouseDown="mouseDown(1)" onMouseOut="mouseUp(1)"/>
</form>
</div>
<table><thead><th>ID</th><th>Name</th><th>Type</th><th>Rating</th></thead><tbody>
<?php include 'getTableData.php'?>
</tbody></table>
</body>
</html>
getTableData.php:
<?php
$servername = "localhost";
$username = "root";
$password = $_POST['pass'];;
$dbname = "testing";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, type, rating FROM crap_food";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"] . "</td><td>" . $row["name"] . "</td><td>" . $row["type"] . "</td><td>" . $row["rating"] . "</td></tr>";
}
} else {
}
$conn->close();
?>
I understand the fact that PHP is run server side, and is only run before any HTML is read by the client, so making a function run when a button is hit wouldn't exactly be possible just using PHP and HTML, but this would be similar to what I'm looking for. I don't want to redirect the user to another page via the form action (Which is why it's blank), I want to keep this all within index.php. Thanks (And sorry for the horrible forming of this question, I'm just a bit confused).
You Use AJAX for this.
$.ajax({
url: 'xxx.php',
data:formData,
cache: false,
contentType:false,
processData:false,
type: 'post',
success: function(response)
{
//do something
}
try this :
$password =$_POST['pass'];
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username,$password);
$sql = 'SELECT firstname FROM users';
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()):
echo ($r['firstname']);
echo "<tr><td>" . ($r['firstname']) . "</td></tr>";
endwhile;
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" .$pe->getMessage());
}
?>
Ok, so I'm making this website (kind of like bitly or goo.gl) where you enter a link and it shortens it, but with some extra goodies.
Right now I'm just hosting a local mysql server for testing, and the way it is setup, once a link is entered to shorten, a random 3 digit code is generated and put into the mysql table, along with its link.
When you enter the code on the site, it goes to the mysql table, finds the code, finds the corresponding link, and in theory is supposed to bring back that link, and then open it.
This is where the problem is. It simply does not work. I cannot figure out whether it is a problem with the html page, or with the scripting but I have no idea.
I'm not very experienced with PHP (language im using for query script) so I'm not sure how to go about troubleshooting.
I was hoping someone on here could offer some insight into why it may be not working.
All I know is when I click the "Go" button, it opens the php code rather than running it, and I'm not sure how to fix it.
Because of me not knowing exactly what the problem is, here is both the html and php code.
HTML:
(stripped down to just body for convenience. nothing interesting anywhere else)
<body>
<center><form action="sql_query.php" method="post">
<input class="enjoy-css" placeholder="" maxlength="3" name="var" type="text" />
<script type="text/javascript" script-name="josefin-sans" src="http://use.edgefonts.net/josefin-sans.js"></script>
<input type="submit" class="enjoy-css_1" value="Go" src="sql_query.php" />
<script type="text/javascript" script-name="josefin-sans" src="http://use.edgefonts.net/josefin-sans.js"></script>
</form></center>
PHP:
<?php
$servername = "localhost";
$username = "nimbleadmin";
$password = "admin";
$dbname = "nimble";
$var = $_POST['var'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysql_query("SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '" + $var + "'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo "id: " . $row["nimblecode"]. " //// URL: " . $row["urlredirect"]. " //// Message: " . $row["messageredirect"]. "<br>";
if ($row["messageredirect"]. == null) {
header('Location: ' . $row["urlredirect"]);
} else {
header('Location: http://nic.x10.mx/message?' . $row["nimblecode"]);
}
$conn->close();
?>
Any help is greatly appreciated! I know it's a bit of a interesting question, but I am still learning!
There is syntax error in your code, please use dot for concatentation in php and use mysqli object while querying instead of mysql.
$result = mysqli_query($conn, "SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '" . $var . "'");
Full Code changes: Store this file in the name as "tinyurl.php"
<?php
$servername = "localhost";
$username = "nimbleadmin";
$password = "admin";
$dbname = "nimble";
$var = $_GET['var'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '%s', $var);
if (!$result) {
echo 'Could not run query: ' . mysql_error(); exit;
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo "id: " . $row["nimblecode"]. "
//// URL: " . $row["urlredirect"]. "
//// Message: " . $row["messageredirect"]. "";
}
if ($row["messageredirect"] == "") {
header('Location: ' . $row["urlredirect"]);
} else if ($row["nimblecode"] != "") {
header('Location: http://nic.x10.mx/message?' . $row["nimblecode"]);
} else {
header('Location: http://nic.x10.mx/');
}
$conn->close();
?>
In .htaccess need to add this rule :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ http://nic.x10.mx/tinyurl.php?var=$1 [QSA,NC,L]
Sample URL entry
http://nic.x10.mx/abc
Will redirect to the target URL present in DB.
If you can't run php code then check if apache's httpd.conf file has PHP MIME type uncommented, besides there are other things to consider. Check this Apache shows php code instead of executing
I recently had my eureka moment when I finished my first database connection. After closing my browser and reopening the html form, the output suddenly changed to code instead of the database values?
HTML form:
<form action="formulier3.php" method="post">
Hoogte: <input type="text" name="height"><br>
Breedte: <input type="text" name="width"><br>
<input type="submit">
</form>
PHP Page:
<?PHP
$user_name = "root";
$password = "root";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM price WHERE height = " . $_POST["height"] . " AND width = " . $_POST["width"] . "";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
print $db_field['ID'] . "<BR>";
print $db_field['value'] . "<BR>";
print $db_field['height'] . "<BR>";
print $db_field['width'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
This is my output:
"; print $db_field['value'] . "
"; print $db_field['height'] . "
"; print $db_field['width'] . "
"; } mysql_close($db_handle); } else { print "Database NOT Found "; mysql_close($db_handle); } ?>
Does anyone knows what's going on here?
Thank you in advance!
Somehow your server has stopped processing your php pages through the php processor (apache module or fastcgi or whatever).
What you see is the effect of presenting your php code as html. The fact that you don't see all your code but rather a small part of it, it is because the part from the first < (in <?php) until the first > (in print $db_field['ID'] . "<BR>"; is being parsed by the browser as an html tag and so it is not printed. If you look at the page source you'll see the full php code.
So there has been some server-side change that has produced that php files are directly server to the browser instead of parsed by the php engine.
One possible cause, is that you are developing in your local computer and when it worked you typed in your browser something like http://localhost/your_page.php but now you are opening the php file directly from the filesystem, so the browser shows something like file:///xampp/htdocs/your_page.php. You should always open your php pages through the web server (ie. using http://localhost/....) and never by double-clicking on the file in the file explorer.