I'm making a simple webpage where anyone can type in a text in a textfiel, and that text will be stored to a database and placed on the screen. At the moment, the text that was posted most recently gets placed at the bottom at the page. I want it to be reversed; the newest at the top and the oldest at the bottom.
Here is my code:
<html>
<head><title>JANNEchat Beta</title></head>
<form action="index.php" method="post" />
<p>Send a message to JANNES database: <input type="text" name="input1" />
</p><input type="submit" value"Submit" />
</form>
</html>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
define('DB_NAME', 'janne');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link){
die('Nu är något vajsing, kunde inte ansluta ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Nu spelas det trix, kan inte hitta databasen ' . DB_NAME . ' : ' .
mysql_error()); }
$value = isset($_POST['input1']) ? $_POST['input1'] : '';
if($value != ''){
$sql = "INSERT INTO janne (String) VALUES ('$value')";
if(!mysql_query($sql)){
die('vajsing: ' . mysql_error());
}
}
mysql_close();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "janne";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT String FROM janne";
$result = $conn->query($sql);
//$a = $result->num_rows - $result->fetch_assoc();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//THE PROBLEM IS HERE, I GUESS.
echo $row["String"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Just update your SQL
$sql = "SELECT String FROM janne ORDER BY id DESC";
Here id may be the Auto Increment field in your table.
Related
Here is my simple php code:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "********"; //hiding my password
$dbname = "course";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM tutors";
$result = $conn->query($sql);
if( $result === true ) {
echo "good";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
while($row = $result->fetch_assoc()) {
echo $row["name"];
}
?>
</body>
</html>
In my database called "course", I have a table called "tutors" which has a column called "name". I have two entries in that table with the names "deep thought" and "pyrenees" respectively.
When this code runs however, the only thing that prints out is:
Error: SELECT name FROM tutors
It is supposed to simply print out the two names that I mentioned before.
Does anyone know why this happens? I know for a fact that I have the two entries in my table!
I think the word "name" is a MySQL reserved word. Wrap your query variables in a tilde backticks like this:
$sql = "SELECT `name` FROM `tutors`";
This helps to escape those values from MySQL thinking you're trying to referencing a built in variable.
Why not use mysqli like so:
function getFollowers($link, $userid)
{
$sql = "SELECT users.id, username, profileImg FROM following INNER JOIN users ON users.id = following.userid WHERE followid = " . $userid;
$result = mysqli_query($link,$sql);
$resultsArray = [];
while($row = mysqli_fetch_assoc($result)) {
$resultsArray[] = $row;
}
mysqli_free_result($result);
return $resultsArray;
}
This is just a clean example, I am sure you get the idea.
Here is what $link is
function connection()
{
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'databaseTable');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
return $link;
}
Or without the methods:
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'databaseTable');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT name FROM tutors";
$result = mysqli_query($link,$sql);
$resultsArray = [];
while($row = mysqli_fetch_assoc($result)) {
echo $row["name"];
}
mysqli_free_result($result);
To check if the query was successful you can do this:
if (mysqli_num_rows($result) > 0)
{
//has rows, so whatever you want with them.
}
You put the condition after defining $result.
I have written following code to connect mysql in php but I am not getting output.
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$mysql_conn = new mysqli($servername, $username, $password);
if ($mysql_conn->connect_error) {
die("Connection failed: ". $mysql_conn->connect_error);
}
echo "Connected successfully";
$name = $_POST["microorganism"];
echo $name;
$db_selected = mysql_select_db('yieldofvanillin', $mysql_conn);
if (!$db_selected){
die ('Can\'t use : ' . mysql_error());
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
$result = $mysql_query($query);
while ($line = myql_fetch_array($result, MYSQL_ASSOC)) {
echo $line["Substrate"];
echo $line["products"];
echo $line["Microorganism"];
echo $line["yield"];
echo $line["Reference"];
}
mysql_close($mysql_conn);
?>
The database name is "yieldofvanillin" and it has five column. I an getting output Connected successfully. After that no output. Please let me know the bug in code.
i have remove errors. which i mention in comments. Code Reference PHP Manual. you should read this manual (strongly recommended)
<?php
$mysqli = new mysqli("localhost", "root", "pravin", "yieldofvanillin");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["Substrate"];
echo $row["products"];
echo $row["Microorganism"];
echo $row["yield"];
echo $row["Reference"];
}
/* free result set */
$result->free();
}
you're mixing mysqli and mysql libraries.
the code should be:
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$mysql_conn = new mysqli($servername, $username, $password);
if (mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_error());
}
echo "Connected successfully";
$name = $_POST["microorganism"];
echo $name;
$db_selected = mysqli_select_db($mysql_conn,'yieldofvanillin');
if (!$db_selected){
die ('Can\'t use : ' . mysqli_error($mysql_conn));
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
$result = mysqli_query( $mysql_conn,$query);
while ($line = mysqli_fetch_assoc($result)) {
echo $line["Substrate"];
echo $line["products"];
echo $line["Microorganism"];
echo $line["yield"];
echo $line["Reference"];
}
mysqli_close($mysql_conn);
?>
Remove error in your code.Read carefully php manual.
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$db = "yieldofvanillin";
// Create connection
$mysqli = new mysqli($servername, $username, $password, $db);
/* connection string*/
if ($mysqli->connect_errno) {
die("Connection failed: " . $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row["Substrate"];
}
$result->free();
}
$mysqli->close();
?>
Your output not showing because mysql_fetch_array is not correct.Because you are mixing mysql_ and mysqli_ functions and you called myql_fetch_array that doesn't exist in mysqli. MySQL and MySQLi are two different PHP extensions and they cannot be mixed. Because the former is deprecated in mysqli
this is form which shows the data which i have to update the data i get correctly i want when i pressed update button the data is update by using up.php file
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "alurdu_db";
$id = $_GET['id'];
mysql_query('SET CHARACTER SET utf8');
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "SELECT * FROM news WHERE news_id='$id'";
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row = $result->fetch_assoc()) {
?>
<form action="up.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control" name="news_title" value="<?=$row["title"]?>">
<div class="col-md-2 text-center">News Title</div>
<button type="submit" class="btn btn-default text-align" style="background-color:#3c8dbc;color:white" value="">Update</button></a>
</form>
<?php
}
} else {
echo "Wrong Page";
}
$conn->close();
?>
this is up.php file i don't know why it does not getting the id if update without id it update all the data of the table
<?php
$news_title = $_POST["news_title"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "alurdu_db";
$news_id = $_GET['id'];
mysql_query('SET CHARACTER SET utf8');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = " UPDATE news SET title='$news_title' WHERE news_id='$news_id' ";
if ($conn->query($sql) === TRUE) {
echo "Updated";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Looks like your SQL statement isn't in closed quotes. It should look like this:
$sql = "UPDATE news SET title='" . $news_title . "' WHERE news_id='" . $news_id . "'";
I am new to PHP. I am creating a login.php page. i have created a table into MySQL database.
Database name: school
Table name: users
I have saved a username = admin and pass= 123
I am now trying to connect the database and trying to verifying the input information from database before accessing to the page "admin.php"
<?php
error_reporting(E_ERROR);
global $link;
$servername='localhost';
$dbname='school';
$dbusername='root';
$dbpassword='';
$table_Name="users";
$link = mysql_connect($servername,$dbusername,$dbpassword);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
else
{
mysql_select_db($dbname,$link) or die ("could not open db".mysql_error());
}
?>
Getting input data from this code
<?php
$my_user = $_POST['user'];
$my_password = $_POST['password'];
?>
trying this
$signin = mysql_query( "SELECT FROM users where username = &my_user" )
or die("SELECT Error: ".mysql_error()); $num_rows = mysql_num_rows($signin);
Now kindly explain with code how can I connect the database and verify the information and if its correct the page should redirect to admin.php page
This will insert the form info into database:
$insert="INSERT INTO `users`(`user`,`password`) VALUES ('$my_user','$my_password') ";
$query=mysql_query($insert,$link);
This will select the info from database:
$result=mysql_query('SELECT * FROM users WHERE username='$my_user' AND password='$my_password'");
$sql1=mysql_query($result,$link);
<?php
if (isset($_POST)) {
$my_user = $_POST['user'];
$my_password = $_POST['password'];
$con=mysql_connect("localhost","root","");
if(!$con)
{
die("Database is not connected");
}
mysql_select_db("school",$con);
$query="select * from users where username=$my_user and pass=$my_password";
$res=mysql_query($query);
if(mysql_num_rows($res) > 0)
header('Location:admin.php'); // redirect to home page
else
echo 'Not found'; // can show some validation err
}
<?php
include('conn.php');
if (isset($_POST['submit'])){
$UserName=$_POST['user'];
$PassWord=$_POST['pass'];
$sql = "SELECT username,pass from login WHERE username='$UserName'and password='$PassWord'";
$retval = mysql_query($sql);
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
if (($row['username']==$Username)and($row['pass']==$Password)){
header("location:admin.php");
}
}
}
echo "Invalid User Name and Password\n";
?>
Start to use PDO for database connections. I have not tested this, but should give you insight into what to do.
config.php
<?php
define('DB_TYPE', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'school');
define('DB_USER', 'root');
define('DB_PASS', '');
?>
functions.php
<?php
function validate_user_creds() {
try
{
$pdo = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME.', '.DB_USER.', '.DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
header('Location: admin.php');
exit();
}
catch (PDOException $e)
{
$error = 'Unable to connect to the database server.';
include 'error.html.php';
exit();
}
}
?>
login.php
<?php
require 'config.php';
require 'functions.php';
if ($_POST['user'] === DB_NAME && $_POST['password'] === DB_PASS) {
validate_user_creds();
}
?>
Normally with mysql (deprecated!)
<?php
error_reporting(E_ERROR);
$error = false;
if(isset($_POST['login']))
{
$servername = 'localhost';
$dbname = 'school';
$dbusername = 'root';
$dbpassword = '';
$table_Name = 'users';
$link = mysql_connect($servername, $dbusername, $dbpassword) or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname, $link) or die ('could not open db' . mysql_error());
$my_user = $_POST['user'];
$my_password = $_POST['password'];
$signin = mysql_query("SELECT * FROM `users` WHERE `username` = '" . mysql_real_escape_string($my_user) . "' AND `password` = '" . mysql_real_escape_string($my_password) . "' LIMIT 1;")
or die('SELECT Error: '.mysql_error());
$num_rows = mysql_num_rows($signin);
mysql_close($link);
if($num_rows)
{
header('Location: admin.php');
}
else
{
$error = 'Unknown login!';
}
}
?><html><head><title>Login</title></head><body>
<form action="#" method="post">
<?php if($error !== false) { echo '<p>' . $error . '</p>'; } ?>
<input name="user" type="text" size="255" />
<input name="password" type="text" size="255" />
<button type="submit" name="login">Login</button>
</form>
</body></html>
PDO / MySQLi
<?php
error_reporting(E_ERROR);
$error = false;
if(isset($_POST['login']))
{
$servername = 'localhost';
$dbname = 'school';
$dbusername = 'root';
$dbpassword = '';
$table_Name = 'users';
$link = new mysqli($servername, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$my_user = $_POST['user'];
$my_password = $_POST['password'];
if(!($signin = $link->prepare('SELECT * FROM `users` WHERE `username` = ? AND `password` = ? LIMIT 1;')))
{
printf("Select Error: %s\n", $link->error);
exit();
}
$signin->bind_param('ss', $my_user, $my_password);
if($signin->execute())
{
$signin->store_result();
$num_rows = $signin->num_rows;
if($num_rows)
{
header('Location: admin.php');
}
else
{
$error = 'Unknown login!';
}
}
$link->close();
}
?><html><head><title>Login</title></head><body>
<form action="#" method="post">
<?php if($error !== false) { echo '<p>' . $error . '</p>'; } ?>
<input name="user" type="text" size="255" />
<input name="password" type="text" size="255" />
<button type="submit" name="login">Login</button>
</form>
</body></html>
Use PDO with prepared statements when you access databases in PHP, since it helps against SQL injection. Have a look at http://php.net/manual/en/intro.pdo.php.
Edit:
Wayne's answer is just confusing. In login.php he is validating the administrator by comparing the user's name to the database name and the user's password to the database's password. I don't recommend it, and it doesn't really have much to do with what you posted.
I'd go with PatrickB's answer.
if(mysql_num_rows(mysql_query("select * from users where username='$my_user' and pass='$my_password'"))>0) {
header('Location:admin.php');
} else {
echo " < b > Incorrect username or password<\b>";
}
As of recently ive been learning php and at that conjuntion in between where i have to now use Mysql in order to keep my bigger info table ogranized, well i wrote this code in order to show the tables (or so i think i did it right). im completely stumped because i can not see any of the displaying tables that i am calling on and the more ive tried the less i works so i was wondering if anyone can see a loop hole in my code or maybe im doing something wrong? or maybe everything ive done is wrong...?
`
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
?>
<?php
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<ul>
<?php
while($subject = mysqli_fetch_assoc($result)) {
?>
<li><?php echo $subject["menu_name"] . "(" . $subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
<?php
mysqli_free_result($result);
?>
</body>
</html>
<?php
mysqli_close($connection);
?>`
Have you forgotten the opening PHP tag at the beginning of your page?
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
Two things i think could be wrong.
Here is a correct implementation to compare. It could be the first PHP opening tag, i also added the default port to the connect statement, and added some try catches with error messages, these can tell if the connect or query is not working.
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
//original connect statement with a port added in
try {
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname , 3306);
} catch(Exception $e) { echo $e->getMessage(); }
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Query looks fine, easier to trouble shoot when its one line, first get it working then break it up
$query = "SELECT * FROM subjects WHERE visible = 1 ORDER BY position ASC";
// This will try to fetch the result and give an error if it can't.
try { $result = mysqli_query($connection, $query);
} catch(Exception $e) { echo $e->getMessage(); }
if (!$result) { die("Database query failed"); }
?>
Is it alright if I alter some of your codes?
See this:
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<?php
/* ESTABLISH CONNECTION */
$connection=mysqli_connect("localhost","juliegri_AAlassa","YourPassword","juliegri_Aalassaly");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* START QUERY */
$result=mysqli_query($connection,"SELECT * FROM subjects WHERE visible='1' ORDER BY position ASC");
?>
<ul>
<?php
/* DO THE WHILE LOOP */
while($subject = mysqli_fetch_array($result)) {
?>
<li><?php echo $subject['menu_name'] . "(" . $subject['id'] . ")"; ?></li>
<?php
} /* END OF WHILE LOOP */
?>
</ul>
</body>
</html>