how to converting mysql into mysqli - php

i have the following problem with a login script. at the moment i refresh my site and would like to change mysql into mysqli. i have a working code, that works with mysql like it should to. now i get in trouble with changing that into mysqli, which doesn't work.
here is the original mysql code:
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
session_register('id');
$_SESSION['id'] = $id;
mysql_query("UPDATE tableA SET time=now(), x4=x4 + 1 WHERE id='$id'");
mysql_query("DELETE FROM tableB WHERE (NOW() - INTERVAL 1 DAY) > Date AND ID='$id'");
$result = mysql_query("SELECT COUNT(*) AS val FROM tableB WHERE ID='$id'");
$count = mysql_fetch_assoc($result);
var_dump($count);
if ($count [val] <xy){
mysql_query("INSERT INTO tableB (Date, ID) VALUES (now(),'$id') ");
mysql_query("UPDATE tableA SET x7=x7 + 1 WHERE id='$id'");
and here is the mysqli version, that wont work and i dont know why:
$time = gmdate("M d Y H:i:s", time());
$id = '".$row["id"]."';
$get_id = "SELECT id FROM tableA WHERE x1='".$x1."' AND x2='".$x2."'";
$result = mysqli_query($db, $get_id);
if ($result === false) {
printf("Errormessage 1");
exit();
}
$row = $result->fetch_array(MYSQLI_ASSOC);
$update = "UPDATE tableA SET time=now(), x4=x4 + 1 WHERE id='".$row["id"]."'";
$result2 = mysqli_query($db, $update);
if ($result2 === false) {
printf("Errormessage 2");
exit();
}
$reset = "DELETE FROM tableB WHERE (NOW() - INTERVAL 1 DAY) > Date AND ID='".$row["id"]."'";
$result3 = mysqli_query($db, $reset);
if ($result3 === false) {
printf("Errormessage 4");
exit();
}
$count = "SELECT COUNT(*) AS val FROM tableB WHERE ID='".$row["id"]."'";
$result4 = mysqli_query($db, $count);
if ($result4 === false) {
printf("Errormessage 5");
exit();
}
$sum = $result4->fetch_assoc($count);
var_dump($sum);
if ($count [val] <xy){
$insert = "INSERT INTO TableB (Date, ID) VALUES(?,?) ";
if($query = $db->prepare($insert)){
$query->bind_param('ss', $time, $id);
$query->execute();
$update_x = "UPDATE tableA SET x7=x7 + 1 WHERE id='".$row["id"]."'";
$result5 = mysqli_query($db, $update_x);
if ($result5 === false) {
printf("Errormessage 5");
exit();

You haven't mentioned the actual error but it seems that problem occurs from here:
$row = $result->fetch_array(MYSQLI_ASSOC);
you didnot use a loop here like your mysql version of code.

You are attempting to insert $time into what appears to be a DATETIME column, based on your old mysql version, but it is improperly formatted.
$time = gmdate("M d Y H:i:s", time());
Based on your use of NOW() in the old code, we assume TableB.Date to be a DATETIME type:
mysql_query("INSERT INTO tableB (Date, ID) VALUES (now(),'$id') ");
So in your new code, since you don't use NOW() for the TableB insert, you should be creating $time as YYYY-MM-DD:
// Should be YYYY-MM-DDD H:i:s for MySQL
$time = gmdate("Y-m-d H:i:s", time());
// It gets inserted into TableB here
$insert = "INSERT INTO TableB (Date, ID) VALUES(?,?) ";
if($query = $db->prepare($insert)){
$query->bind_param('ss', $time, $id);
$query->execute();
Or, just use MySQL's NOW() in the new code unless you have a reason to specify the time in PHP code:
$insert = "INSERT INTO TableB (Date, ID) VALUES(NOW() ,?) ";
if($query = $db->prepare($insert)){
$query->bind_param('s', $id);
$query->execute();

Related

How to LOOP a SELECT query until it finds a data on database (PHP to MySQL)

I wanted to select a row in the database, but if row is not in the database, it should loop until it finds the
This line
$prev_date = date('M d, Y', strtotime($macrodate .' -1 day')); transforms the currentdate to one down (lets say Jun 15, it will transform to Jun 14). And use that date to check if the date is in the database, it not, it will loop and go to Jun 13. Until it could find the date.
How do I do this? What loop should I use?
$query = "SELECT * FROM users_macros WHERE userid = '$userid' AND `date` = '$macrodate'";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) == 0) {
while(1) {
$prev_date = date('M d, Y', strtotime($macrodate .' -1 day'));
$query2 = "SELECT * FROM users_macros WHERE userid = '$userid' AND `date` = '$prev_date'";
$result2 = mysqli_query($con, $query2);
if (mysqli_num_rows($result2) != 0) {
$row2 = mysqli_fetch_assoc($result2);
$targetcarbs = $row2['carbs'];
$targetproteins = $row2['proteins'];
$targetfats = $row2['fats'];
$con->query("INSERT INTO users_macros VALUES('','$userid','$targetproteins','$targetfats','$targetcarbs','$macrodate')");
break;
}
}
}
Don't use a loop. Just use a query that returns the row with the highest date lower than $macrodate. And you can combine that with the INSERT query.
And add a NOT EXISTS criteria to make it select nothing if the given date is already in the table.
Also, use a prepared statement to prevent SQL injection.
$stmt = mysqli_prepare($con, "
INSERT INTO users_macros
SELECT '', userid, proteins, fats, carbs, ? FROM users_macros
FROM users_macros
WHERE userid = ? AND date < ?
AND NOT EXISTS (
SELECT 1 FROM users_macros
WHERE userid = ? AND date = ?
)
ORDER BY date DESC
LIMIT 1");
mysqli_stmt_bind_param($stmt, "sss", $macrodate, $userid, $macrodate, $userid, $macrodate);
mysqli_stmt_execute($stmt);

Identifying time in & time out in a column

I have a Library system for time in & out for the students. The students can go in when they want and go out when they want. This is how it works: There is a barcode on each student ID. They need to hover under the scanner every-time they pass the door, which automatically saves the Data.
Here is my code for saving.
<?php
$scan=$_GET["scan"];
include("connection/mysqlconnect.php");
$sql="SELECT * FROM student where Barcode like('$scan%')";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count==1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$crs_id = $row['course_id'];
}
$my_date = date("Y-m-d h:i:s", strtotime("+7 hours"));
$sql="insert into dtr
(students_id,course_id,Date_Time)values('$id','$crs_id','$my_date')";
$result = $conn->query($sql) or die(mysqli_error());
mysqli_close($conn);
}
?>
The above code works perfectly.
But, I want to identify if it is in or out in a single column.
Below is my sample table. I want to add the In-Out Column.
Student_ID Course_ID Date_Time In-Out
11 4 2018-02-09 08:31:05 in
22 5 2018-02-09 09:35:09 in
22 5 2018-02-09 09:45:08 out
11 4 2018-02-09 10:01:05 out
22 5 2018-02-09 11:35:09 in
My problem is: I want to identify if the last hover is "in", in the column "In-Out" and the system will save the "out".
The simple way would be to select the records from the dtr table for that student/course combination and just fetch the last one...
$sql="SELECT `In-out` as lastAccess FROM `dtr` where Student_ID = $id
order by Date_Time desc limit 1";
$result2 = $conn->query($sql);
$count2=mysqli_num_rows($result2);
$lastAccess = 'out';
if( $count2 == 1 ) {
$row = mysqli_fetch_assoc($result2);
$lastAccess = $row['lastAccess'];
}
$lastAccess = ( $lastAccess == 'out' )? 'in':'out';
This will go after the first SQL to check the student and before the insert. The insert can then use $lastAccess.
Note that if a row in this table isn't found, the value of $lastAccess is 'out' (set prior to the test and therefore the bit which inverts this will set a new value of 'in' as it's the first time this student has used the system.
Here #Nigel
<?php
$scan=$_GET["scan"];
include("connection/mysqlconnect.php");
$sql="SELECT * FROM student where Barcode like('$scan%')";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count==1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$crs_id = $row['course_id'];
}
$my_date = date("Y-m-d h:i:s", strtotime("+7 hours"));
$sql="SELECT `in-out` as lastAccess
FROM `dtr`
where student_id = $id
order by Date_Time desc
limit 1";
$result2 = $conn->query($sql);
$count2=mysqli_num_rows($result2);
$lastAccess = 'out';
if( $count2 == 1 ) {
$row = mysqli_fetch_assoc($result2);
$lastAccess = $row['lastAccess'];
// Check
echo "in-out=".$lastAccess.PHP_EOL;
}
$lastAccess = ( $lastAccess == 'out' )? 'in':'out';
// Check
echo "next in-out=".$lastAccess.PHP_EOL;
$sql="insert into dtr (students_id,course_id,Date_Time,in-out)values('$id','$crs_id','$my_date','$lastAccess')";
$result = $conn->query($sql) or die(mysqli_error($conn));
mysqli_close($conn);
}
?>

SQL update & insert

I have a MYSQL table named issues_tot including following columns:
v_code, oid, amount, mod_date
02) Then I need to update or insert records of the table according to the given condition as follows:
if(($vt == $vote)||($of == $ono)){
03) update is working properly, but insert is not (else part). My code is showing below:
if (isset($_POST["submit"]))
{
$ono =$_POST["oid"];
$amt =$_POST["amt"];
$allo=mysql_fetch_array(mysql_query("SELECT * FROM allocation WHERE al_code='{$_GET['al_code']}'"));
$vote=$allo['v_code'];
$current_date = date("Y-m-d H:i:s");
$query ="select * from issues_tot where v_code='$vote' ";
$result = mysql_query($query) or die ( mysql_error());
$row = mysql_fetch_assoc($result);
$vt = $row['v_code'] ;
$of = $row['oid'] ;
if(($vt == $vote)||($of == $ono)){
$query ="UPDATE issues_tot SET oid = $ono, amount = amount + $amt WHERE v_code=$vote";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
}else {
$query ="INSERT INTO issues_tot (v_code, oid, amount, mod_date) VALUES ('$vote', '$ono', '$amt', '$current_date')";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
}
}
I can not understand what I am going wrong. Can anyone help me ?. Pls

sql server update when WHERE exist

I have sql + php query and i need inform user when update fail exmpl:
$sql = "UPDATE db SET
date = GetDate(),
...
...
...
WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2'
";
sqlsrv_query( $con, $sql);
And now if php variables values not 100% match values in db update fails but users cant see that. He can check records and try again. I would like inform him when query update nothing.
Like GOB commented, you can use the PHP sqlsrv_rows_affected function to retrieve the number of affected rows. For example:
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_rows_affected( $stmt );
if ($row_count === false)
echo "Error in retrieving row count.";
else
echo $row_count;
Before directly executing update query,check whether condition in update query exists or not. This can be done by selecting count of that condition.
Try below code:
$sql = "select count(*) as count from db WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2' ";
while($row = mysqli_fetch_array($sql))
{
$count = $row['count'];
}
if($count == 0)
{
echo 'update will fail';
}
else
{
$sql = "UPDATE db SET
date = GetDate(),
...
...
...
WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2'
";
}

Fetch data but INSERT results only once a day

I have a function which fetches data from my database, it counts a number of instances existing for the same user and gives me a total figure. But I want to store this value in another table, which it does just fine the problem is that every time a user refreshes a page the same data is inserted and I want it to be inserted only once.
my function:
public function getYesterday($user){
$user = "SELECT user_id FROM tbl_user WHERE ott_email='$user'";
$query = mysqli_query($this->con(), $user);
$count = mysqli_num_rows($query);
if($count == 1){
while($row = mysqli_fetch_assoc($query)){
$id = $row['user_id'];;
}
$yesterday = "SELECT COUNT(tbl_template_log.user_id) FROM tbl_template_log ";
$yesterday .= "WHERE tbl_template_log.user_id='$id'";
$yesterday .= " AND DATE(send_date) = DATE(NOW() - INTERVAL 1 DAY)";
$query_yesterday = mysqli_query($this->con(), $yesterday);
$result = mysqli_fetch_row($query_yesterday);
$insert = "INSERT INTO tbl_statistics (user_id, sta_count, sta_date)VALUES ('$id', '$result[0]', NOW())";
mysqli_query($this->con(), $insert);
echo $result[0];
}
}
Looking at my function logic and structure could someone suggest a correct solution to make sure the insert query is done only once per day.....?
I am using PHP, and MySQL

Categories