I'm trying to add values to an array after getting data from a mysql query, this obviously involved a while ($x = mysql_fetch_array($MysqlQuery)) {} as seen below:
$CheckTime = mysql_query("SELECT * FROM cp11641_timetable.booking");
$dates = array();
while ($date = mysql_fetch_array($CheckTime)) {
$DateInt = strtotime($date['Date']);
//echo $DateInt . " ";
$dates[] = $DateInt;
echo $dates[1] . " ";
}
However when I echo $dates[x], it'll display the value in the x position of the array, but it'll show it by (x+1) times (i.e. $dates[0] will show 'a' once, $dates[1] will show 'b' twice, and $dates[2] will show 'c' thrice)
How do I fix this? What's causing the problem?
$CheckTime = mysqli_query($mysql_connection, "SELECT * FROM cp11641_timetable.booking");
$dates = array();
while ($date = mysqli_fetch_assoc()($CheckTime)){ // Use mysqli_* for queries.
$DateInt = strtotime($date['Date']); // This will show an UNIX timestamp
$dates[] = $DateInt; // Fills the array with the timestamp.
}
Your problem is that you use mysql_fetch_array. But then try to use $date['Date']. If you want to use the column names as indices in the $date array. You need to use mysql_fetch_assoc().
On a different note and as mentioned in the comments use the mysqli_* extension or PDO. In this answer I've used mysqli_*
Please note the $mysql_connection in the mysqli_query function.
MySqli Query Doc
Most likely if you use the code below it should work as intended.
Still strongly advise to switch to mysqli_*
$CheckTime = mysql_query("SELECT Date FROM cp11641_timetable.booking");
$dates = array();
while ($date = mysql_fetch_array($CheckTime)){
$DateInt = strtotime($date[0]);
$dates[] = $DateInt;
}
foreach($dates as $timestamp){
echo $timestamp . '<br/>';
}
This works, make sure to put in your correct credentials to connecting to your database on step #1. everything else false in place.
<?php
/* ==============================================
This is the new way of connecting to database
using mysqli
================================================*/
// Step #1 create credentiasl for database connection
$host = ""; //type your host ex. localhost between the quotes
$user = ""; //your username between the quotes
$pass = ""; //your password between the quotes
$db = ""; //your database you are connecting to between the quotes
// step #2 create connection to database
$conn = new mysqli($host, $user, $pass, $db);
//step #3 check and see if connection is working and error free
if ($conn->error) {
die("Could not connect to the database");
} else{
// create array dates
$dates = array();
// create select statement
$CheckTime = ("SELECT * FROM cp11641_timetable.booking");
// query the the database using the connection
$sql_CheckTime = $conn->query($CheckTime);
// if rows available in table add them to array dates
while ($row = mysqli_fetch_assoc($sql_CheckTime)) {
$dates[] = $row;
}
//optional uncomment bottom line to check if dates array has data will display as array on webpage
// var_dump($dates);
// loop through array
foreach ($dates as $date){
// echo out data you want to display. 'Date' = column name
echo strtotime($date['Date']) . "<br>";
};
};
?>
I recommend you to using mysql_fetch_assoc() and then display the dates horizontally or vertically with html/css style.
Sorry if my answer is bad choose.
Related
I want to send a reminder to my subscribers a month before their subscription ends, i have columns validity and reminder (type VARCHAR) in my MYSQL DB
date stored in those columns are saved using php date function
$validity = date('d/m/Y',strtotime("6 months"));
$reminder = date('d/m/Y',strtotime("5 months"));
now i want to send a mail when the current date is equals reminder date
I have a test entry with reminder value 22/06/2017 and $date variable echo the same value.
$date = date('d/m/Y');
$q = 'SELECT * FROM subscriptions WHERE reminder = "$date"';
$r = mysql_query($q);
if(!$r){
echo 'query err';
}
$a = mysql_num_rows($r);
echo 'No of rows returned '.$a;
*mailing script after this line*
this script outputs No of rows returned 0
Can someone give me some idea how i should approach this
First i suggest you your date format is change in database and type change datetime.
This format follow for you insert reminder date
$reminderdate = date('Y-m-d');
Then compare with currentdate when fetch data from database:
$date=date('Y-m-d');
if($r['reminder']==$date)
{
echo 'Mail sent here';
}
else
{
echo 'date not match';
}
Your script is at risk for SQL Injection Attacks, see this
The issue is here:
'SELECT * FROM subscriptions WHERE reminder = "$date"';
change it to:
"SELECT * FROM subscriptions WHERE reminder = '".$date."'";
to compare date, you have to wrap it into single quotes '
A few suggestions:
the reminder column may be redundant depending on your logic
in the future please use different approach to connect to the database, for example: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
the validity column should rather be DATETIME format
Now to your main question - it can be because of datetype mismatch so switch in database to DATETIME and in PHP use date('Y-m-d').
First Of all You should not store date in varachar.
Now to compare dates in varchar first you have to convert the string(varchar) into date.
for that you can use mysql's function:
str_to_date
You can get the example how to convert it and then compare it to get the result.
$q = "SELECT * FROM subscriptions WHERE reminder = '{$date}'";
I Know You have selected the answer already and ignored the comments, because you just want to get this done with and move on no matter how you did it. I will just make this answer a community WIKI.
Below are the things you need to note :
The API that you are using have depreciated for a long time ago rather use mysqli or even better PDO with prepared statements.
Also What I'm sure when the use subscrips on your website, you should have a column that stores the duration of the subscription and the actual expire date and a flag to identify expired subscriptions.
Mysql does provide its own date time functions, which you can use and use the date type on these columns.
Use API that is still active and maintained that is mysqli_* or pdo they both support prepared statements.
$host = '127.0.0.1';
$db = 'DBNAME';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
);
$dbh = new PDO($dsn, $user, $pass, $opt);
$stmt = $dbh->query("SELECT * FROM subscriptions WHERE subscriptionsExpireColumn = DATE_ADD(CURDATE(), INTERVAL 1 MONTH)");
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
} else {
$results = $stmt->fetchall();
if (count($results) > 0) {
foreach ($results as $row) {
//DO WHAT EVER YOU WANT TO DO WITH THE RESULTS
}
} else {
echo "no records found";
}
}
?>
It out puts the the results of the equation but dose not update the DB?? I have another connection open in the code at this point via mysql...
<?php
if($user_new=='Yes'){
$end = strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00')) - 1;
$now = time();
$time = $end - $now;//Seconds til end of month
$percent = $time / 2635200;
$minus_1 = 1 - $percent;
$server = 'XXXXXXX';
$user = 'XXXXXXX';
$pass = 'XXXXXXXX';
$db = 'XXXXXXX';
$con = mysqli_connect ($server, $user, $pass, $db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_ID = get_current_user_id();
mysqli_query($con,"UPDATE usermeta SET value=$minus_1
WHERE user_id='$user_ID' AND meta_key='user_new_mo'");
$user_per = $global_bal * $minus_1;//2635200 = Seconds in 30.5 days
$minus_per = $global_bal - $user_per;
$echo = $minus_per * $user_ghs;
}
elseif($user_new>='0'){
$num_result = mysql_query("SELECT value FROM usermeta WHERE user_id='$user_ID' AND meta_key='user_new_mo'", $hash_con);
$echo = $num_result;
}
Try a prepared statement to help with variable substitution.
$stmt = $mysqli->prepare("UPDATE usermeta SET value=? WHERE user_id=? AND meta_key=?");
$stmt->bind_param($minus_1,$user_ID,'user_new_mo');
$stmt->execute();
$stmt->close();
In mysql query you must want to differ the php variables and the string like this Eg.
mysql_query($con,"select * from users where userid='".$user_id."'")
For eg the if $user_id=ssoft then the query resembles like this,
select * from userid where userid='ssoft'.
IAM SURE IT WILL HELP YOU.
Let's assume first that you have no mysql errors (I see you're not checking that in your code)... Most probably your update problem (not updating) should have something to do with the $user_ID.
Check to make sure that "get_current_user_id()" returns a value that exists in the [user_id] column in your table.
Next... If the "get_current_user_id()" isn't the problem, then the problem is in your query (I think this is most probable): whenever you have to deal with variables inside a string, use curly braces.
So, turn
WHERE user_id='$user_ID'
into
WHERE user_id='{$user_ID}'
Or simply concatenate it like:
$query = "SELECT * FROM `x` WHERE `some_column` = '" . $someValue . "'";
Use of curly braces for variables inside a string is valid only if the string is wrapped in double quotes (your's is, so you're ok here), otherwise $someVar is simply the string $someVar (ie $string = '$someVar') as opposed to $someVar = 'abc'; $string = "{$someVar}"; - then $string becomes abc
Also, this being an integer (I suppose) there would be no need for the quotes, but it should still work (unlike the other way around, if you would want to enter a string without quotes).
I have a script that inserts a company id, user id and a datetime of the transaction when someone enters their email. Now I have to add a dropdown select box that allows for the user to select the number of donations they want to make so the only have to enter their email address once. What is the best way to go about this? I was thinking something like this:
$coid = $row['companyid'];
$userid = $_SESSION['userid'];
$selectbox = $_POST['select']; // number value 1-10
// old query
mysql_query = ("INSERT INTO donations(company, user)");
// new query
$i=1
while($i<=$selectbox) {
mysql_query = ("INSERT INTO donations(company, user)");
$i++
}
or something along those lines. Is that the best way to go about it? Better ways?
First, stop using mysql_ functions as they are being deprecated. Use mysqli_ or PDO functions instead.
You should use prepared statements or sanitize your variables to prevent against SQL injection.
Regarding a better approach, you can put them into an array then implode when executing. This is a good starting point. It uses PDO to insert an array.
With your current code, I'm not clear how you're tracking the number of users wishing to do donations, but you can do something like:
$i = 1;
while($i <= $selectbox) {
$insertArray[] = "$coid, $userid";
$i++;
}
mysql_query("INSERT INTO donations (company, user) VALUES (" . implode('), (', $insertArray) . ")");
You should make a database table with 3 columns (for this question).
I will give you the code to make the required table, just copy and paste this into PHPmyAdmin:
Create Table donations(
company_id int,
user_id int,
donate_num int,
datetime DATETIME
)
Then use the INSERT INTO function to update the database using the new mysqli functions (Replace the server/username etc with your database details):
$mysqli= new mysqli('SERVER','USERNAME','PASSWORD','DATABASE NAME')
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
function escapeStringSlash($value) {
global $mysqli;
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = $mysqli->real_escape_string($value);
}
return $value;
}
$coid=escapeStringSlash($row['companyid']);
$userid = escapeStringSlash($_SESSION['userid']);
$selectbox = escapeStringSlash($_POST['select']);
$date = new DateTime();
$currentTime = $date->format("Y-m-d H:i:s");
if($insertDonations=$mysqli->query("INSERT INTO donations(company_id,user_id,donate_num,datetime) VALUES(".$coid.",".$userid.",".$selectbox.",'".$currentTime."')"){
echo "Number of donations received";
}else{
echo "There was a problem inserting this.";
}
$mysqli->close();
I currently have a relatively large HTML form (100+ fields). I want to take the data from that form and upload it to a mySQL database when the use hits submit. I have created the PHP code below and have been slowly adding fields and testing to see if the connection is successful. Everything was working through $skilled_nursing, but when I added the next set of values I am no longer successfully creating database entries. All of my echo commands are displayed and I am not getting failures in my error log, but the data is not being received in the database.
Can anyone see what is going wrong? I have checked multiple times for spelling errors, but I haven't seen any. I am wondering if I am somehow timing out with the connection or if I am trying to stick too many values into the execute command.
<?php
echo 'started ok';
// configuration
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "dbname";
$dbuser = "dbuser";
$dbpass = "userpass";
echo 'variables assigned ok';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
echo 'connection established';
// new data
$facility_name = $_POST['facility_name'];
$facility_street = $_POST['facility_street'];
$facility_county = $_POST['facility_county'];
$facility_city = $_POST['facility_city'];
$facility_state = $_POST['facility_state'];
$facility_zipcode = $_POST['facility_zipcode'];
$facility_phone = $_POST['facility_phone'];
$facility_fax = $_POST['facility_fax'];
$facility_licensetype = $_POST['facility_licensetype'];
$facility_licensenumber = $_POST['facility_licensenumber'];
$facility_email = $_POST['facility_email'];
$facility_administrator = $_POST['facility_administrator'];
$skilled_nursing = $_POST['skilled_nursing'];
$independent_living = $_POST['independent_living'];
$assisted_living = $_POST['assisted_living'];
$memory_care = $_POST['memory_care'];
$facility_type_other = $_POST['facility_type_other'];
$care_ratio = $_POST['care_ratio'];
$nurse_ratio = $_POST['nurse_ratio'];
// query
$sql = "INSERT INTO Facilities (facility_name, facility_street, facility_county, facility_city, facility_state, facility_zipcode, facility_phone, facility_fax, facility_licensetype, facility_licensenumber, facility_email, facility_administrator, skilled_nursing, independent_living, assisted_living, memory_care, facility_type_other, care_ratio, nurse_ratio) VALUES (:facility_name, :facility_street, :facility_county, :facility_city, :facility_state, :facility_zipcode, :facility_phone, :facility_fax, :facility_licensetype, :facility_licensenumber, :facility_email, :facility_administrator, :skilled_nursing, :independent_living, :assisted_living, :memory_care, :facility_type_other, :care_ratio, :nurse_ratio)";
$q = $conn->prepare($sql);
$q->execute(array(':facility_state'=>$facility_name,
':facility_street'=>$facility_street,
':facility_county'=>$facility_county,
':facility_city'=>$facility_city,
':facility_state'=>$facility_state,
':facility_name'=>$facility_name,
':facility_zipcode'=>$facility_zipcode,
':facility_phone'=>$facility_phone,
':facility_fax'=>$facility_fax,
':facility_licensetype'=>$facility_licensetype,
':facility_licensenumber'=>$facility_licensenumber,
':facility_email'=>$facility_email,
':facility_administrator'=>$facility_administrator,
':skilled_nursing'=>$skilled_nursing,
':independent_living'=>$independent_living,
':assisted_living'=>$assisted_living,
':memory_care'=>$memory_care,
':facility_type_other'=>$facility_type_other,
':care_ratio'=>$care_ratio,
':nurse_ratio'=>$nurse_ratio));
echo 'query parsed';
?>
This doesn't exactly answer what's going wrong with your code, but it might help solve it.
I would do this a bit differently. You say that you have a lot of fields. Your code is likely to get very long and repetitive. Since it looks like your form field names already correspond with your table columns, I would do something more like this (not tested):
// get a list of column names that exist in the table
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name = 'Facilities'";
$q = $conn->prepare($sql);
$q->execute();
$columns = $q->fetchAll(PDO::FETCH_COLUMN, 0);
$cols = array();
foreach ($_POST as $key=>$value)
{
// if a field is passed in that doesn't exist in the table, remove it
if (!in_array($key, $columns)) {
unset($_POST[$key]);
}
}
$cols = array_keys($_POST);
$sql = "INSERT INTO Facilities(". implode(", ", $cols) .") VALUES (:". implode(", :", $cols) .")";
$q = $conn->prepare($sql);
array_walk($_POST, "addColons");
$q->execute($_POST);
function addColons($value, &$key)
{
$key = ":{$key}";
}
This way, you could have 10, 100, or 1000 fields and this code won't have to change at all. You also reduce your chance for typo errors because there's only one place where the column name is specified. You don't have to worry about SQL injection on the column names because you check to make sure that the column exists before allowing it to be used in your query.
This does, of course, assume that all fields passed in via $_POST correspond with column names in your table. If this isn't the case, it may be easiest to just store those particular field values that aren't columns in separate variables and unset() them from the $_POST array.
I have a webpage written in HTML. I have a dropdown list that is populated by a database utilizing a MySQL query:
<SELECT NAME = "Participant" STYLE = "WIDTH: 187" TITLE="Begin typing participant last name for fast searching." required>
<OPTION SELECTED VALUE = "">Select Participant...</OPTION>
<?PHP
$allParticipants = getall_participants();
foreach($allParticipants as &$value) {
$dt = date('Y-m-d');
$val = $value->get_id();
$optval = $dt.$val;
echo "<OPTION VALUE='",$optval,"'>";
echo $value->get_first_name()," ",$value->get_last_name();
echo "</OPTION>";
}
?>
</SELECT>
The getall_participants() looks like:
function getall_participants () {
connect();
$query = "SELECT * FROM dbParticipants ORDER BY last_name";
$result = mysql_query ($query);
$theParticipant = array();
while ($result_row = mysql_fetch_assoc($result)) {
$theParticipant = new Participant($result_row['last_name'],
$result_row['first_name'], $result_row['address']);
$theParticipants[] = $theParticipant;
}
mysql_close();
return $theParticipants;
}
And on this same page I have a textbox that is pre-filled-in by another database:
<?php
$dt = date('Y-m-d');
$participants = getall_dbParticipantEntry_byDate($dt);
foreach($participants as &$value) {
$a = $a.$value.", ";
}
echo "<INPUT TYPE='text' NAME='Participants' STYLE='WIDTH:50px;' TITLE='Participants' ";
echo "VALUE='[", $a.' ', "]'/>";
?>
That getall_dbParticipantEntry_byDate($date) looks like:
function getall_dbParticipantEntry_byDate($date) {
connect();
$query = 'SELECT * FROM dbParticipantEntry WHERE date = "'.$date.'"';
$result = mysql_query ($query);
$theParticipantEntry = array();
while ($result_row = mysql_fetch_assoc($result)) {
$theParticipantEntry = new ParticipantEntry($result_row['date'], $result_row['id'], $result_row['call_time'],
$result_row['result'], $result_row['notes']);
$theParticipantEntries[] = $theParticipantEntry->get_id();
}
mysql_close();
return $theParticipantEntries;
}
However, while both of these functions work fine individually, when they're both on the same webpage (like I meant them to be), only the one that comes first runs. I tested this by switching them in and out. They both complete their designated tasks, but only when alone on the page.
How can I get them both to run and populate their respective fields?
Thanks so much.
Try the following order:
Connect to mySQL server
Do task 1
Do task 2
Close Connection
For me it looks, like you have closed the mysqlconnection, before you do task2.
Edit:
Maybe you can do it like that?
function f1 ()
{
$res = mysql_connect(...);
// .. do some queries ..
mysql_query($sql, $res);
mysql_close($res )
}
function f2 ()
{
$res = mysql_connect(...);
// .. do some queries ..
mysql_query($sql, $res);
mysql_close($res )
}
Edit:
From php.net:
Be careful when using multiple links to connect to same database (with same username). Unless you specify explicitly in mysql_connect() to create a new link, it will return an already open link. If that would be closed by mysql_close(), it will also (obviously) close the other connection, since the link is the same.
Had lot of trouble figuring it out, since in <=4.3.6 there was a bug which didn't close the connection, but after the patch to >=4.3.7, all my application broke down because of a single script that did this.
You run them both on the same connection. You need to store the resource id returned from mysql_connect and pass this to each mysql method (each uses it's own relevant resource).
that said, I think it is time to:
Move to something more modern like Mysqli or PDO extensions. Much better API
Use some kind of abstraction on the connection managment, preferably one instance of a DB managment class per connection. Plenty of examples on the web, and it is way above the scope of this site to provide such instructions.