Pinterest style of text - php

I'm creating a news feed site. User can upload text and then it displays the texts below eachother. I want to display all the texts in a way that Pinterest displays pictures. How can I do this?
The code for displaying and getting the text from the database is:
<?php
//connect
mysql_connect("host","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
//query the database
$getnews = mysql_query("SELECT * FROM news ORDER BY id DESC") or die(mysql_query());
while ($row = mysql_fetch_assoc($getnews))
{
//get data
$id = $row['id'];
$title = $row['title'];
$body = $row['body'];
$date = $row['date'];
echo "
<b>$title posted on $date</b><br>
";
echo nl2br($body);
echo "<hr>
";
}
?>
And the code for posting a text is like:
<?php
//insert category to database
if(isset($_POST['qty'])) {
// Fetch and clean the <select> value.
// The (int) makes sure the value is really a integer.
$qty = (int)$_POST['qty'];
// Create the INSERT query.
$sql = "INSERT INTO `table`(`quantity`)
VALUES ({$qty})";
// Connect to a database and execute the query.
$dbLink = mysql_connect('host', 'username', 'password') or die(mysql_error());
mysql_select_db('database_name', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
// Check the results and print the appropriate message.
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if ($_POST['post'])
{
//get data
$title = $_POST['title'];
$body = $_POST['body'];
//check for existance
if ($title&&$body)
{
mysql_connect("host","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$date = date("Y-m-d");
//insert data
$insert = mysql_query("INSERT INTO news VALUES ('','$title','$body','$date')") or die(mysql_error());
die("Your text has been posted!");
}
else
echo "Please fill out your name and text<p>";
}
?>

Related

PHP/Mysqli check before update

Hey I am completely new to PHP/MySqli, I would like to check before update if Scanstatus field of given ID is already "Scanned". if its already Scanned display a message as "Already Scanned" else Update.
Below code only update and doesn't check if already exists.
<?php
$id = $_POST['id'];
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno())
{
echo "failed to connect " . mysqli_connect_error();
}
if(isset($_POST['Submit']))
{
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = $id";
$result = mysqli_query($connection,$query);
if (!$result) {
die('Error' . mysqli_error($connection));
}
else
{
echo "Successfully updated";
}
}
?>
Try following php code
$id = $_POST['id'];
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno())
{
echo "failed to connect " . mysqli_connect_error();
}
else{
if(isset($_POST['Submit']))
{
$sql = "UPDATE sales SET ScanStatus = 'Scanned' WHERE id = '$id'";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "Successfully updated";
} else {
die('Error' . mysqli_error($connection));
}
}
}
When click SUBMIT button "isset($_POST['Submit'])" will be true and direct into if statement. then run sql command and is if there is any result that sql query affected go into next if statement after true the condition "$result->num_rows > 0" then echo "Successfully updated".
As I understand, you want to update only if the ScanStatus field is not Scanned
So you can modify you existing query like this without the need to fetch the record:
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = $id AND `ScanStatus` != 'Scanned'";
Just change the query to above and use:
if(mysqli_affected_rows($result) > 0 ){
Here is a full code:
<?php
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno()) {
echo "failed to connect " . mysqli_connect_error();
}
if(isset($_POST['Submit'])) {
$id = $_POST['id'];
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = $id AND `ScanStatus` != 'Scanned'";
$result = mysqli_query($connection, $query);
if(mysqli_affected_rows($connection) > 0 ){
echo "Successfully updated";
}
else {
echo 'Already Scanned';
}
}
You can use this code:
Use if(mysqli_affected_rows($mysqli) > 0 ) or no comparison at all.
Replace your code with this:
<?php
$id = $_POST['id'];
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno())
{
echo "failed to connect " . mysqli_connect_error();
}
if(isset($_POST['Submit']))
{
$my_query = mysqli_query($connection, "SELECT * FROM `sales` WHERE `id` = ". $id . " AND `ScanStatus` = 'Scanned'");
if(mysqli_num_rows($my_query) > 0){
echo "Already ScanStatus is Scanned";
}
else{
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = ".$id;
//echo $query;die;
$result = mysqli_query($connection, $query);
if(mysqli_affected_rows($connection) > 0 ){
echo "Successfully updated";
/* get new updated data */
$new_query = mysqli_query($connection, "SELECT * FROM `sales` WHERE `id` = '$id' LIMIT 1");
$new_info = mysqli_fetch_array($new_query);
echo "<pre>"; print_r($new_info);
}
else
{
echo "Not updated";
}
}
}
?>

adding HTML form input to database

Kindly need assistance in my coding, I have a database named Books with table called OpenBooks I would like to add the html form which are user inputs into the table and echo confirmation.
<?php
$Title = $_POST['Title'];
$Author = $_POST['Author'];
$Series = $_POST['Series'];
$Price =$_POST['price'];
//database connection
$connection = mysqli_connect('localhost', 'root', '','books');
if(!$connection){
die("Database connection failed");
}
$query = "INSERT INTO OpenBooks(Title,Author,series,price)";
$query .= " VALUES ('$Title', '$Author', '$series', '$price')";
$result = mysqli_query($connection, $query);
}
?>
if (!$result) {
die('Invalid query: ' . mysql_error());
}
else {
echo 'yay, done';
}
And you need $Price instead of price and rest of variables starting from capital letter.

How to delete a record from mysql using a button?

I would like to be able to delete a row using the delete-button I display at the end of each row. I need two queries to delete a person from my database completely since I have a n-m relationship between Persons and Functions.
The queries are as follows:
delete from `Persons` where `Person ID` = '1';
I would like to implement these queries using the delete-button provided in the actual code, how can I do this?
UPDATE:
I made changes according to what Kristian Hareland wrote, and it reloads but the person isn't deleted, what should be changed to make it work?
showall.php:
<table>
<thead>
<tr>
<?php
// Variables
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "CISV";
$dberror1 = "Could not connect to database: ";
$dberror2 = "Could not select database: ";
$dberror3 = "Could not execute query: ";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1 . mysql_error());
$select_db = mysql_select_db('CISV') or die ($dberror2 . mysql_error());
$query = "SELECT p.`Person ID`, p.`First Name`, p.`Last Name`, p.Gender, p.`Date Of Birth`, p.Email, p.`Phone Number`, c.Region, c.Country, p.`Delegation ID`
FROM Persons as p, Chapters as c
WHERE c.`Chapter ID`=p.`Chapter ID`
ORDER BY p.`Delegation ID";
$result = mysql_query($query) or die($dberror3 . mysql_error());
$row = mysql_fetch_assoc($result);
foreach ($row as $col => $value) {
echo "<th>";
echo $col;
echo "</th>";
}
?>
</tr>
</thead>
<tbody>
<?php
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) {
?>
<tr>
<?php
foreach($row as $key => $value){
echo "<td>";
echo $value;
echo "</td>";
}
?>
<td>Delete</td>
</tr>
<?php } ?>
DeletePerson.php:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "CISV";
$dberror1 = "Could not connect to database: ";
$dberror2 = "Could not select database: ";
$dberror3 = "Could not execute query: ";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1 . mysql_error());
$select_db = mysql_select_db('CISV') or die ($dberror2 . mysql_error());
$UserId = mysql_real_escape_string($_GET['id']);
if(isset($UserId)){
//DELETE QUERY
$Del = mysql_query("DELETE FROM `Persons` WHERE `Person ID` = '$UserId'");
if($Del){
$Flag = TRUE;
}
else{
$Flag = FALSE;
}
header("Location: /showall.php?delete=$Flag");
}
else{
die("Error");
}
I would use JavaScript and Ajax here.
Make a Html-button with an onclick function like delete_user();
delete_user() calls a .php file to validate the rights and execute some mysql-delete promts.
The .php file returns a boolean to the JavaScript.
You could catch that boolean up and inform the user about the result.
IMHO best way is create separate file functions.php
<?php
//functions.php
$id = filter_this($_POST[id]);
mysql_query("delete from Persons_Functions where `Person ID` = '$id');
?>
and send there via JQuery:
function deleteuser(id){
$.post("admin_action.php", {action:'delete_user',id:id}, function(data){
if(data.trim()=="done"){
console.log("OK!");
});
}}
Without JS You can use HTML (just change BUTTON to A):
<a href='script.php?action=delete&id=12'>DELETE</a>
and PHP:
$id = $_GET[id];//filter this value
mysqli_query($link, "DELETE FROM users WHERE ID='$id'"); //use mysqli
I would use the GET method for this
<?php foreach ($results as $result): ?>
Delete
<?php endforeach; ?>
At the top of index.php
if (isset($_GET['action']) && $_GET['action'] == 'delete') {
if (isset($_GET['id']) && intval($_GET['id']) != 0) {
$id = intval($_GET['id']);
$stmt = "delete from table where id='{$id}'";
}
}
Just use a link:
<tbody>
<?php
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) {
?>
<tr>
<?php
foreach($row as $key => $value){
echo "<td>";
echo $value;
echo "</td>";
}
?>
<td>Delete</td>
</tr>
<?php } ?>
</tbody>
DeletePerson.php:
<?php
$UserId = mysql_real_escape_string($_GET['id']);
if(isset($UserId)){
//DELETE QUERY
mysql_query("DELETE FROM Persons WHERE Person ID = '$UserId'");
mysql_query("DELETE FROM Persons_Functions WHERE Person ID = '$UserId'");
header("Location: /showall.php?flag=deleted");
}
else{
die("Error");
}

Retrieve information from database in a variable

I am trying to create a variable in my php code where I can use a value from my database to use user information. Basically, I'm trying to fetch the UserID from the database desikitchen where it matches the variable $dkuser.
Can anyone tell me where I'm going wrong?
$sqlStremail = "SELECT UserID
FROM User
WHERE Name = '$dkuser'";
$result = mysql_query($sqlStremail);
$row = mysql_fetch_assoc($result);
$variable = $row["UserID"];
$sql2 = "INSERT INTO desikitchen.Inventory (ItemName, ItemUser)
VALUES ('{$itemname1}', '{$sqlStremail}')";
$result = mysql_query($sql2);
You better Use MySQLi class library. Something like this:
$mysqli = new mysqli("",$mysqlUser,$mysqlPass,$mysqlTable);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
print FALSE; exit();
}
$query = "SELECT UserID FROM User WHERE Name = '$dkuser'";
$result=$mysqli->query($query);
if($mysqli->query($query)==False) {print mysqli_error($mysqli); exit();}
if($result->num_rows>0)
{ $row = $result->fetch_array();
echo $row["UserID"];
} else
{ echo "User not found"; }

Combining all INSERT statements into one

I'm creating a page for a class and I have lots of different while loops with lots of different INSERT statements. I didn't think there would be a problem with that until I discovered that they weren't being inputed right. They were all inputed but what happened was that they were all inputed in separate rows as opposed to being one entry across their individual columns. I need it so that all of the INSERT statements are combined into one while still checking to make sure that the full name isn't yet in the database. Please help me rewrite my code so that it can do just that.
Here is the code that needs to be rewritten so that it just has one INSERT statement:
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$name = mysql_real_escape_string($_POST['firstname']);
$query = "SELECT * FROM names_1 WHERE firstname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your first name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE lastname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your last name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (lastname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['firstname'] . " " . $_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE fullname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your full name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (fullname) VALUES('$name')";
$result = mysql_query($query);
}
$age = mysql_real_escape_string($_POST['age']);
$query = "INSERT INTO names_1 (age) VALUES('$age')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else {
echo "Your name couldn't be added to the database!";
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
When inserting a row with multiple columns you can just combine the two groups of keys and values like so:
INSERT INTO names_1 (firstname, lastname) VALUES ('John', 'Smith')
The other alternative is in your database mark both the Firstname and Lastname as Unique columns. Then you can do the following.
INSERT INTO names_1 (firstname, lastname) VALUES ('John', 'Smith') ON DUPLICATE KEY UPDATE names_1 SET x="blah" WHERE blah
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
This should accomplish what you are setting out to do.
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$fullname = mysql_real_escape_string($_POST['firstname'] . " " . $_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE fullname='" . $fullname . "'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your full name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname, lastname, fullname, age) VALUES('" . $_POST['firstname'] . "','" . $_POST['lastname'] . "','" . $fullname . "'," . $_POST['age'] . ")";
$result = mysql_query($query);
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css"/>
<?php include("Header.php"); ?>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>

Categories