Delete PHP Data from MYSQL after display - php

After the data is displayed I want the exact text to get deleted from MySQL
I have a random generator that gets data from a row and displays it random
Architecture :
"minecraft" and inside the table its a row named "list"
<?php
// Connect to database server
mysql_connect("localhost", "bdweb_panel", "password") or die (mysql_error ());
// Select database
mysql_select_db("bdweb_panel") or die(mysql_error());
$strSQL = "SELECT * FROM minecraft";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Array to hold all data
$rows = array();
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// add row to array.
$rows[] = $row;
}
// Close the database connection
mysql_close();
// Max rand number
$max = count($rows) - 1;
// print out random combination of data.
echo $rows[rand(0, $max)][0] . " "
?>
Update :
To be more explicit
This is the architecture from the DB
and the php page with a refresh button
Each time a user is pressing the refresh button he gets a data from the DB (EX : test1, and if he press once again test2 or test3 or test 4 - all random data) all random. Once he gets for example test 1, the text 1 data from the DB deletes so it will not be generated once more again, so after he press the refresh button he will display a data and at the same time he will delete it from the data base.

Since mysql is deprecated you should use mysqli and prepared statements;
Heres a short example how to delete a mysql entry
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$stmt = $mysqli->prepare("DELETE FROM table WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
But if you just want to delete the column of an entry you need to use an UPDATE query
$stmt = $mysqli->prepare("UPDATE table SET column = ? WHERE id = ?");
$stmt->bind_param('si',$new_value, $id);
$stmt->execute();
where $new_value can be null or whatever you want to.

If I understand correctly your question:
<?php
...
$max = count($rows) - 1;
$r = rand(0, $max);
/// if $rows[$r][0] is ID column
mysql_query("delete from minecraft where id = ".$rows[$r][0];
OR
mysql_query("update minecraft set list='' where id=".$rows[$r][0];
echo $rows[$r][0];
?>

Update :
To be more explicit
This is the arhitecture from the DB http://i.stack.imgur.com/crvh0.png and the php page with a refresh button http://i.imgur.com/F1Q3mAx.png
Each time a user is pressing the refresh button he gets a data from the DB ( EX : test1 , and if he press once again test2 or test3 or test 4 - all random data ) all random . Once he gets for example test 1 , the text 1 data from the DB deletes so it will not be generated once more again , so after he press the refresh button he will display a data and at the same time he will delete it from the data base.

Related

Displaying only selected values from database

<?php
$sql = "SELECT * FROM team;";
$result = mysqli_query($conn, $sql );
$row = mysqli_fetch_row($result);
$teamname = $row[1];
echo $teamname;
Consider table in DB consists of 10 names from 1-10. That will be displayed on the screen as usually (using retrieving), but the problem is when I click any name from 1-10 displaying on the screen that should open a new page by displaying only the particular name I selected.
I tried this but, all the values are displaying.
First, add to your mysql table a column called "ID" to associate a number to each name.
After you can direct the user to your page like this
Name n.1 // etc..
so you can take the id of your name using GET and display to your page only that name
(Always use Prepared Statement even when it is not strictly necessary)
PHP script
$name_id = $_GET['id'];
// connect to your db
$stmt = $db->prepare("SELECT * FROM team WHERE ID = ?");
$stmt->bind_param("s",$name_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
echo $result['name'];
if you need anything else, comment below.

Insert data into a column if no data in column

How do I insert data into a column if that column has no values? This piece of code will not insert any values, unless I take out the if statement. Of course that isn't what I want, since that means each time the code is run, more data will be inserted into the column 'datagroup'.
include('dg_config.php');
# select column datagroup from table data
$stmt = $db -> prepare("SELECT datagroup FROM data");
$stmt->execute();
# fetch rows from data
while($row = $stmt->fetch()){
if (empty($row['datagroup'])){
$insertdg = "INSERT INTO data (datagroup)
VALUES ('Data Definitions'),('Policies'),('Systems and Process Documents'),('Purchase Orders'),('Invoices')";
$db ->exec($insertdg);
}
}
P.S dg_config.php contains the variable $db which is used for MySQL connection. Also, I have no values in the column so UPDATE won't work.
Desired output:
If you want to check if there are no records first and only insert the values then, a quick way from where you are is to say if the fetch() fails to retrieve a row then do the insert...
include('dg_config.php');
# select column datagroup from table data
$stmt = $db -> prepare("SELECT datagroup FROM data");
$stmt->execute();
if ( !$stmt->fetch() ){
$insertdg = "INSERT INTO data (datagroup)
VALUES ('Data Definitions'),('Policies'),('Systems and Process Documents'),('Purchase Orders'),('Invoices')";
$db ->exec($insertdg);
}
// re fetch the data
$stmt->execute();
This removes the while() loop altogether.

How to fetch latest data(as it is entered) form database automatically

How to fetch latest data(as it is entered) from database automatically to my web page using PHP, AJAX, JQuery?
I used the following code and it is working fine. but I need to fetch and display an updated data on my web page as soon as a new data is entered in my database.
<?php
$hostname = '127.0.0.1';
$username = 'xxxxxxxxxxx';
$password = 'xxxxxxxxxxx';
try {
$dbh = new PDO("mysql:host=$hostname;
dbname=sensor_measurements",
$username, $password);
/*** The SQL SELECT statement ***/
$sth = $dbh->prepare("
SELECT `dtg` AS date,
`temp` AS temperature,
`humid` As humidity,
`acous` As acoustic,
`accel_x` As accelx,
`accel_y` As accely,
`accel_z` As accelz
FROM `sensor_data`
ORDER BY date DESC
LIMIT 1
");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$json_data = json_encode($result);
echo $json_data;
?>
In the js save the last id of the data fetched, then simply compare it. For example create a query in php that only fetches the id, and run it every 5 seconds if the id differs, than fetch the php code that you posted.

Obtain record from MySQL strip tags then update

I have a field (Description) in a MySQL database (poi). I wish to use php and the strip_tags to remove the HTML from all the records in the database. I then want to update the result to the same Description field in the database.
I have no problem with obtain the string and stripping the HTML, but I just can't seem to work out how to update the database with the result.
// check connection
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$sql_article = "SELECT Description FROM poi";
$result = $mysqli->query($sql_article);
// Iterates through the MySQL results
while ($row = $result->fetch_array())
{
$Description_no_html = strip_tags($row['Description']);
printf("%s<br />\n", $Description_no_html);
}
Ideally each row will have a unique id column that you can use to specify which row to update using a prepared statement:
$sql_article = "SELECT id, Description FROM poi";
$result = $mysqli->query($sql_article);
$stmt = $mysqli->prepare("UPDATE poi SET Description = ? WHERE id = ?");
// Iterates through the MySQL results
while ($row = $result->fetch_array())
{
$Description_no_html = strip_tags($row['Description']);
printf("%s<br />\n", $Description_no_html);
$stmt->bind_param("si",$Description_no_html,$row['id']);
$stmt->execute();
}
If you don't have a unique id column, then use the following statement instead
$stmt = $mysqli->prepare("UPDATE poi SET Description = ? WHERE Description = ?");
and
$stmt->bind_param("ss",$Description_no_html,$row['Description']);
Alternative: stripping tags directly in mysql
You can create a custom mysql function that strips tags (https://stackoverflow.com/a/13346684/3574819) and use the following query
UPDATE poi SET Description = strip_tags(Description)
Disclaimer: I'm not sure how well the above referenced mysql strip_tags works, so your mileage may vary depending on your content.

Pull Column Data with PDO

Okay I have been able to pull a random account and pull one account as long as I predefine it but now im curious as to how to pull a account based on the Account Number
So basicly if the account number matches pull all the data for that row.
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db'] ['dbname'], $config['db']['username'], $config['db']['password']);
$AccountNumber = "uwoi1002"
$query = $db->query("SELECT `content`.`ProfilePic` FROM `content`");
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$Hello = $row['ProfilePic'];
echo '<html><img src="http://www.MYDOMAIN.COM/Content/';
echo $Hello;
echo '"></html>';
}
?>
So what this is doing is returning everyones profile pics on one page Not quite what I want
I have it where in a feild on my mysql data base it has a unique Id for each account I would like it to randomly pic one of those then return all the data for that row
FirstName
LastName
Gender
City
State
FacebookUrl
BirthMonth
BirthDay
BirthYear
AccountNumber - This is the one I want to pull based on
ProfilePic
ProfilePicCaption
So basically pick a random row and pull all the data instead of displaying all the data for one column
Thank you any and all help is awesome and at least now im using secure code
It sounds like you jsut need a WHERE clause...
// the ?, called a placeholder will have the value substituted for it
$stmt = $db->prepare("SELECT `content`.`ProfilePic` FROM `content` WHERE id = ?");
// an array of values for the placeholders in the query
$stmt->execute(array(2));
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
// do stuff with data
}
Alternatively if you can use named placeholders which i would recommend if you have a query with lots of parameters:
// the :id, called a placeholder will have the value substituted for it
$stmt = $db->prepare("SELECT `content`.`ProfilePic` FROM `content` WHERE id = :id");
// an array of values for the placeholders in the query
$stmt->execute(array(':id' => 2));

Categories