I have a JSON file that brings data in to iOS. I also want it to see if there are more than 2 records.
If there is more than 2 records i want it to delete everything apart from the last 2 records
How do I insert this in to this php file
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM test ORDER BY id DESC LIMIT 1";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
You are using LIMIT 1 which will mean you only get 1 record back. Are you planning on increasing the limit?
You could always use the PHP count() function and the array_slice() function if you need to cull down an array of records returned...
http://php.net/array_slice
Related
My code executes but only for the most recent row stored in the database. It doesn't check through the other rows and keeps executing on the same data in the recent row. What function am I missing?
Adding while(true) condition, which now loops but only loops the most recent.
$db = mysqli_connect("" , "", "") or die("Check connection parameters!");
// Optionally skip select_db and use: mysqli_connect(host,user,pass,dbname)
mysqli_select_db($db,"ds_main") or die(mysqli_error($db));
if (mysqli_connect_error()) {
die ('Failed to connect to MySQL');
} else {
/*SUCCESS MSG*/
echo '';
}
$sqlCommand = "SELECT companyname, domainurl, expirationdate FROM domains WHERE expirationdate BETWEEN CURDATE() AND CURDATE()+INTERVAL 30 DAY";
$query = mysqli_query($db, $sqlCommand) or die (mysqli_error($db));
//fetch the data from the database
$domainnames = "domainurl";
$domaindate = "expirationdate";
while ($row = mysqli_fetch_array($query)) {
$domainnames = $row['domainurl']; // list of expiring URLs
$domaindate = $row['expirationdate']; // list of expiry dates
} // that's it for the loop
if (count($domainnames) > 0 ) {
//carrys out a task
}
// Free the results
mysqli_free_result($query);
//close the connection
mysqli_close($db);
}
?>
I expect the code to execute across all rows, not just the most recent. I'm new to php.
Your code is "executing" on all rows, but on each row it's overwriting the values of $domainnames and $domaindate with the latest row's values. I suspect you are probably intending to build an array of domain names and dates, more like so:
$domainnames = array(); // list of expiring URLs
$domaindate = array(); // list of expiry dates
while ($row = mysqli_fetch_array($query)) {
$domainnames[] = $row['domainurl']; // add to list
$domaindate[] = $row['expirationdate']; // add to list
} // that's it for the loop
I have a page that displays entered data from a database in a table. I am wondering how I can reverse the order displayed from newest to oldest.
Here is the code for the fetch page that displays my results in the table, html has been removed as it is irrelevant to the question.
<?php
// Create connection in mysqli
$connection = new mysqli($server, $user, $pass, $dbname);
//Check connection in mysqli
if($connection->connect_error) {
die("Error on connection:" .$connection->connect_error);
}
//Display the informaion
$sql = "SELECT * FROM logs";
$res = $connection->query($sql);
if($res->num_rows > 0) {
// echo table row code
while($row = $res->fetch_assoc()) {
// echo table row code
}
}
else {
echo "No Record Found!";
}
$connection->close();
?>
Simply modify your query like this :
$sql = "SELECT * FROM logs ORDER BY `column` DESC";
Where column is your column with the primary key. Normaly it is ID or id...
I have tables in one db, and one is foreign keyed to the other. My problem is that I'm trying to call up information stored in one table based on the user name which links the 2 tables stored in the other. Here is my php, mind you I'm pretty fresh on the databasing and php, so cut some slack. Here is my code:
<?php
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
while($row = mysql_fetch_assoc($gal_result,MYSQL_ASSOC))
{
foreach($results['shoot_name'] as $result)
{
echo $result['shoot_name'], '<br>';
if(mysql_num_rows($gal_result) !=1) {
die("No galleries found for this user.");
}
}
}
You can google "PHP PDO tutorial" and find many resources. Here's one that is very clear and well written: like: https://phpdelusions.net/pdo
Here's a better example:
<?php
$loaduser = $_SESSION['username'];
// use PDO, not the deprecated mysql extension
$dsn = "mysql:host=localhost;dbname=user_register";
$conn = new PDO($dsn, "DB_USER", "DB_PASS");
// set exception errmode, so code dies automatically if there's an error
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// use a parameterized query instead of concatenating variables into SQL
$sql = "SELECT shoot_name FROM images WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$loaduser]);
// fetch all into an array of results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// check the count of the results with < 1 instead of != 1
// in case it's 2 or more
if ($stmt->rowCount() < 1) {
die("No galleries found for this user.");
}
// loop through results
foreach($results as $row) {
// use dot for string concatenation instead of comma.
echo $row["shoot_name"] . "<br>";
}
$results has to be fetched before tryin to get its contents.
While trying to get its contents you were fetching $row instead of $results
You are using mysql, mysql has been deprecated try using mysqli or PDO in the future.
Try this anyway.
<?php
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
$results = mysql_fetch_assoc($gal_result,MYSQL_ASSOC)
while($results = mysql_fetch_assoc($gal_result,MYSQL_ASSOC)){
foreach($results['shoot_name'] as $result) {
echo $result['shoot_name'], '<br>';
if(mysql_num_rows($gal_result) !=1){
die("No galleries found for this user.");
}
}
}
?>
Try rewriting to this untested snippet (in case you want to keep using deprecated code ;))
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
if(mysql_num_rows($gal_result)==0){ // returns number of rows so if 0 there are no rows
die("No galleries found for this user.");
}
while ($row = mysql_fetch_array($gal_result)) { // "while" is already your loop. No need for the foreach within.
echo $row['shoot_name'], '<br>';
}
If you want to select from multiple tables with some reference try this query:
$gal_result= mysql_query("SELECT shoot_name FROM images AS a LEFT JOIN your_other_table AS b ON a.username = b.username WHERE a.username='$loaduser'") or die (mysql_error());
Like anyone i would advise you on using more up to date code.
See here for more info: http://php.net/manual/de/function.mysql-query.php
This is probably a simple error, but I'm stumped...
I have a database that has entries inserted using AJAX on a chrome extension, which works great and inserts instantly.
I have a separate PHP file that is being used to output the number of entries in a table. This works, but is takes a long time for the entries to update to the right number when called. I need it to be up to date instantly.
Is there any reason why it's taking so long for the query to output the correct number, when the table itself is updating instantly?
<?php
$link = mysqli_connect("localhost", "root", "", "fyp");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = mysqli_query($link, "SELECT * FROM links")) {
$row_cnt = mysqli_num_rows($result);
printf($row_cnt);
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
Thanks.
I think you should simple run:
if ($result = mysqli_query($link, "SELECT count(*) AS `nr` FROM links")) {
$row_cnt = mysqli_fetch_assoc($result);
printf($row_cnt['nr']);
mysqli_free_result($result);
}
It will be the best one. Or if your links are not removed at all you could run:
if ($result = mysqli_query($link, "SELECT id FROM links ORDER BY id DESC LIMIT 1")) {
$row_cnt = mysqli_fetch_assoc($result);
printf($row_cnt['id']);
mysqli_free_result($result);
}
Hand off the processing to the database by using an aggregate query and return a scalar result with mysqli_result:
if ($result = mysqli_query($link, "SELECT COUNT(1) FROM links")) {
$row_cnt = mysqli_result($result, 0);
printf($row_cnt);
mysqli_free_result($result);
}
Ok I will try to explain, (I am Portuguese lol).
I have a Database where I have the fallowing MySQL:
Database: ad
Table: notebooks
Fields: ID, tag, so, lastlogon, lastlogh
My ldap query gets data from ldap server (active directory) and stores it in my MySQL database (ad/notebooks).
I get tag which is tag number is unique.
I get so which is the OS installed in the notebook.
I get lastlogh which is the last logon time stamp, and it is unique too.
ID field is auto increment and key but I can set the tag filed to be key.
I have a config_notebooks.php where I set all the variables to connect to ldap and MySQL servers.
<?php
/*------------------------------------------------------------------------*/
//setting your variables
/*------------------------------------------------------------------------*/
//ldap host
$host = "ldap://HEICPT1VIA01.HEIWAY.NET";
//ldap user
$user = "domain\user";
//ldap password
$pswd = "pssw";
//ldap base structure
$dn = "OU=NotebookM2,OU=WorkstationsM2,OU=PT1,DC=heiway,DC=net";;
//attributs to search and get
$attrs = array("cn","operatingsystem","lastlogon");
//sql host
$sqlhost="localhost";
//sql user
$sqluser="root";
//sql password
$sqlpswd="";
//sql database
$database="ad";
//sql table
$table="notebooks";
?>
Now the query script
<?php
/*------------------------------------------------------------------------*/
//Query script
/*------------------------------------------------------------------------*/
include 'config_notebooks.php';
$filter = $_POST['filter']."=".$_POST['keyword']."*";
//connect to db
$con = mysql_connect("$sqlhost","$sqluser","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//connect to active directory
$ad = ldap_connect($host)
or die( "Could not connect!" );
// Set version number
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3)
or die ("Could not set ldap protocol");
// Binding to ldap server
$bd = ldap_bind($ad, $user, $pswd)
or die ("Could not bind");
$search = ldap_search($ad, $dn, $filter, $attrs)
or die ("ldap search failed");
$entries = ldap_get_entries($ad, $search);
$sel = mysql_select_db("ad", $con);
if (!$sel)
{
die('Could not select DB: ' . mysql_error());
}
for ($i=0; $i<$entries["count"]; $i++)
{
$tag = $entries[$i]["cn"][0];
$so = $entries[$i]["operatingsystem"][0];
$lastl = $entries[$i]["lastlogon"][0];
mysql_query("
INSERT INTO
$table (tag, so, lastlogh)
VALUES
('$tag', '$so', '$lastl')
ON DUPLICATE KEY UPDATE
tag='$tag',
so='$so',
lastlogon='$lastl'
");
}
mysql_close($con);
ldap_unbind($ad);
if ($entries["count"] > 0)
header("Location: notebooks_list.php")
?>
In this query the last logon timestamp is coded like 130276262860634000
So I can export everything to excel and decode it, but I found a code that does that, so it saves time.
I created a new field in the database (lastlogon) and I need to fetch the data from lastlogh field, decode with the new script and store it in the lastlogon field.
This is the script that I found:
<?php
function adConvert ($ad) {
$seconds_ad = $ad / (10000000);
//86400 -- seconds in 1 day
$unix = ((1970-1601) * 365 - 3 + round((1970-1601)/4) ) * 86400;
$timestamp = $seconds_ad - $unix;
$normalDate = date("F d, Y", $timestamp);
return $normalDate;
}
//example: echo adConvert($ad);
?>
Using Mysql API
$res = mysql_query("SELECT * FROM $table");
while($row = mysql_fetch_assoc($res)) {
$logon_ts = adConvert($row['lastlogh']);
mysql_query("UPDATE $table SET lastlogon = '$logon_ts' WHERE tag='$row[tag]'");
}
I hope this solves your problem.
Note: Mysql API is deprecated as of PHP 5.5.0. So, It's highly recommended to use Mysqli API for newer developments.
man.. use the distinct for resolve u problem http://www.w3schools.com/sql/sql_distinct.asp