SQL Select issue with PHP - php

My site is successfully inserting date from values the user has entered, however, when it comes to getting data from the database I have a problem.
Here's my code:
$sql = "SELECT cost FROM settings LIMIT 1";
if ($conn->query($sql) === TRUE)
{
$cost = $sql;
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
I'm just getting an error (Error: SELECT cost FROM settings LIMIT 1) and I'm unsure how to identify the problem. Everything looks correct from my point of view, obviously it's not.

Try this code. This code works only if you have properly connected to DB.
$sql = "SELECT `cost` FROM `settings` LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["cost"];
}
} else {
echo "0 results";
}

Try using backtics,
$sql = "SELECT `cost` FROM `settings` LIMIT 1";
And also,
if ($sql->num_rows > 0) {
.....

Actually the error is in.
if ($conn->query($sql) === TRUE)
{
}
$conn->query($sql) will not return TRUE for SELECT QUERY ,it will return a result object. So the condition becomes false and you are getting the else part printed.

Related

How do I increment a unique receipt number using PHP and update it in mysql database?

I am trying to increment a receipt number and add that new receipt number in the mysql database.
Here is my code that i have written:
<?php
require 'config.php';
$sql = "SELECT * FROM receipts ORDER BY id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$date = date("ymdhs");
$row2 = $row['id'];
$recnum = $date.'-00'.($row2+);
echo $recnum ;
$sql = "UPDATE receipts SET recnum='$recnum' WHERE id='$row2'";
if ($conn->query($sql) === TRUE) {
echo "updated";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
The order is not specified in your select query. Thus, you get no guarantees from your RDBMS that your data will come back in a certain order - or even in a consistent order - unless you query your data with an ORDER BY clause.
If you want to rely on this order, you must specify your desired order using ORDER BY.
"$row2+" wont increment $row2, use (++$row2) - plus plus should be before the variable- instead.
I have managed to debug my code.
here is the working code.
<?php
require 'config.php';
$sql = "SELECT * FROM receipts ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$date = date("ymdhs");
$row2 = $row['id'];
$recnum = $date.'-00'.$row2;
echo $recnum ;
$sql = "UPDATE receipts SET recnum='$recnum' WHERE id='$row2'";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>

Do i need to select before delete in mysql?:

In my websites admin page, i can delete products from the webshop, with this php code below. (Ajax calls this php file).
My question is, that do i need to select and check the num rows, or drop that, and just keep and run the delete queries?
<?php
include_once("../../files/connect.php");
if($_POST)
{
$id = mysqli_real_escape_string($kapcs, $_POST['id']);
$check = mysqli_query($kapcs, "SELECT termek_id, termek_thumb, termek_big FROM termek WHERE termek_id='$id' LIMIT 1");
if(mysqli_num_rows($check) > 0 )
{
/*Galéria törlése, ha van*/
$check_gallery = mysqli_query($kapcs, "SELECT * FROM gallery WHERE gallery_termek_id = '$id'");
if(mysqli_num_rows($check_gallery) > 0 )
{
while($gall = mysqli_fetch_assoc($check_gallery))
{
$DestinationDirectory = "../../images/gallery/";
if(file_exists($DestinationDirectory.$gall['gallery_thumb']))
{
unlink($DestinationDirectory . $gall['gallery_thumb']);
}
if(file_exists($DestinationDirectory.$gall['gallery_big']))
{
unlink($DestinationDirectory . $gall['gallery_big']);
}
mysqli_query($kapcs, "DELETE FROM gallery WHERE gallery_termek_id = '$id'") or die(mysqli_error($kapcs));
}
}
/* Címkék törlése, ha van */
$check_cimke = mysqli_query($kapcs, "SELECT termek_cimke_termek_id FROM termek_cimke WHERE termek_cimke_termek_id = '$id'");
if(mysqli_num_rows($check_cimke) > 0 )
{
mysqli_query($kapcs, "DELETE FROM termek_cimke WHERE termek_cimke_termek_id = '$id'");
}
mysqli_query($kapcs, "DELETE FROM hir_termek_kapcsolo WHERE hir_termek_kapcs_termek = '$id' ") or die("Delete error 2 - " . mysqli_error($kapcs));
$del = mysqli_query($kapcs, "DELETE FROM termek WHERE termek_id = '$id'");
if($del)
{
echo 'Delete ok';
}
else
{
echo 'Delete error;
}
}
else
{
echo 'Nincs ilyen azonosítójú termék.';
}
}
?>
You do not need to select anything before deleting any rows. Just use the same condition as you would selecting the rows.
Run the delete query, and you can check the number of affected rows to see if anything was deleted or not, and if so, how many rows. This function returns and integer with the number of deleted rows for a DELETE query.
mysqli_query($kapcs, "DELETE FROM hir_termek_kapcsolo WHERE hir_termek_kapcs_termek = '$id' ") or die("Delete error 2 - " . mysqli_error($kapcs));
echo mysqli_affected_rows($kapcs)." rows deleted";
http://php.net/manual/en/mysqli.affected-rows.php
WARNING
You're already using an API that supports prepared statements with bounded variable input, you should utilize parameterized queries with placeholders (prepared statements) to protect your database against SQL-injection!
Get started with mysqli::prepare() and mysqli_stmt::bind_param().
You do not need to select before you delete.
If no rows match the conditions, then the delete will not delete any rows.

How do I loop through the update query in php and display it so it is like a log history

<?php
include('core/init.php');//database connection
if(isset($_POST['btn_submit'])){
$sqlQuery = mysql_query("UPDATE `position` SET `ATR`='".mysql_real_escape_string($_POST['ATR'])."',
$resultQuery = mysql_query($connection, $sqlQuery) or die (mysql_error($connection));
if(mysql_affected_rows($resultQuery) > 0){
echo "updated";
}else{
echo "failed";
}
header('Location:position2.php');
$result = mysql_query("SELECT * FROM position WHERE ID='" .$_POST["id"]. "'");
$row2 = mysql_fetch_array($result);
}
?>
//What this code does it it updates the database based on user input and I am trying to loop through each of the user input as update and display but it doesn't seem to work
($_POST['ATR'])."',
Is missing a closing "
Also formatting code makes it easier to read and debug.

PHP - Check table to see if entry exists

I need to check if a record exists in a table before adding it.
I've done some digging and this is what people keep coming back too:
$result= mysql_query("SELECT id FROM mytable WHERE city = 'c7'");
if(mysql_num_rows($result) == 0) {
// row not found, do stuff...
} else {
//row found, do other stuff...
}
or some variation there of.
This logic is exactly what I need except for the fact that $result is never returning a positive result.
The record does exist and should return a positive result.
I also tried
$sql="SELECT COUNT(email) FROM table WHERE email=$mail;";
$yesorno = mysqli_query($sql);
echo $yesorno ;
as a test and the echo returns no value.
you need to check first if the query succeed running maybe there is a problem with it
$Query = "Select id from mytable where city = 'c7' ";
if($result = mysql_query($Query)) {
if ( mysql_num_rows($result) == 0 ) {
// no rows found ;
} else {
// row exist ;
}
} else {
echo "Query failed ". $Query;
}

Php Mysql update statement not working (Syntax is correct)

I am not sure why my database is not being updated. The code runs and the success message is displayed but database remains the same. I have checked my syntax numerous times and have added mysql_error but I am not sure whats wrong.
if (!empty($username) && !empty($extension) && !empty($location)) {
$q2 = mysql_query("SELECT * FROM `intranet`.`mmg_locations` WHERE `id`='{$location}' ") or die (mysql_error()) ;
$r2 = mysql_fetch_assoc();
$q = mysql_query("UPDATE `intranet`.`mmg_cpd_users` SET `name` = '{$username}', `extension` = '{$extension}', `location`='{$location}'
WHERE `id` = '{$id}' ") or die (mysql_error());
if ($q) {
echo '<p style="color: green;">The user '.$username.' has been successfully updated.</p>';
}
}
Print $q in the browser before executing. Copy the whole UPDATE statement from browser and directly execute in phpmyadmin query browser
$q = "UPDATE `intranet`.`mmg_cpd_users`
SET `name` = '{$username}',
`extension` = '{$extension}',
`location`='{$location}'
WHERE `id` = '{$id}' ";
echo $q;
die();
if ($q) {... }

Categories