I'm attempting to run a while statement that will set a column in a mysql database, based on a uniqueID.
I've done this many times, and I'm not sure what I am doing wrong this time.
Basically, it works properly until I actually tell it to save the table. Here is my code
$alertAdmin = mysqli_query($con, "SELECT * FROM tickets WHERE notified='0'");
$tcheckNotifs = mysqli_num_rows($alertAdmin);
if($tcheckNotifs > 0) {
echo "test<br><br>";
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
$sql = "UPDATE tickets SET `notified`='1' WHERE `UniqueID`='$Unique'";
//mysqli_query($con, $sql);
}
}
And this works for echoing the UniqueID, and it echos the correct one. The problem comes in when I uncomment the mysqli_query($con, $sql);
in which case, nothing inside the loop is echo'd, but it DOES save the database.
For example:
Lets say this while statement loops through and finds 3 iterations of rows that have notified equal to 0 (UniqueID's 29, 26, 25), while the mysqli_query is commented, it will display these numbers on the page just fine. But as soon as I uncomment it, the database will save but it does not display any of the rest of the while loop on the page.
I need this desperately, because I plan to send a desktop notification at the same time the loop is played.
FOLLOW UP:
It also does not display the echo "test<br><br>"; on the page when the query is uncommented either.
Another follow up:
The query is saving all the data like its meant to. The problem is nothing else inside the tcheckNotifs IF statement are showing (echo's and such), like they aren't being executed. Almost like the end of the while statement is executing before anything else, including the "test" echo before the while statement.
Could anyone help me figure out why this isn't working as expected?
Here is all of my current code, with some suggestions from you guys added in, but still not working properly.
The while statement will save the query, but no other output is shown on the page.
$configs = include("config.php");
$con = mysqli_connect($configs['SQL-Host'], $configs['SQL-User'], $configs['SQL-Pass'], $configs['SQL-Database']) or die("Error " . mysqli_error($con));
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$alertAdmin = mysqli_query($con, "SELECT * FROM tickets WHERE notified='0'");
$tcheckNotifs = mysqli_num_rows($alertAdmin);
if($tcheckNotifs > 0) {
echo "test<br><br>";
flush(); ob_flush();
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
updateTickets($con, $Unique);
}
echo "test<br><br>";
}
function updateTickets($con, $id){
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$id";
mysqli_query($con, $sql);
}
FINAL UPDATE
With the help of Alex Andrei as well, we moved to PDO
$dsn = 'mysql:dbname=domains;host=localhost';
$user = 'root';
$password = '';
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$st = $db->prepare('SELECT UniqueID FROM tickets WHERE notified=0');
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $d){
echo $d['UniqueID'] . "<br/>";
$id = $d['UniqueID'];
$st = $db->prepare("UPDATE tickets SET notified=1 WHERE UniqueID=$id");
$st->execute();
}
SECOND UPDATE
Try putting your query in a variable and run the loop like this...
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$Unique";
$update = mysqli_query($con, $sql);
}
UPDATE
There is a chance the query runs first like you said. Maybe you can create an independent function to run the query and call the function from inside the while loop.
function updateTickets($con, $id){
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$id";
mysqli_query($con, $sql);
}
And your loop would look like this...
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
updateTickets($con, $Unique);
}
ORIGINAL ANSWER
I would modify your query like this...
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$Unique";
You do not need all the back ticks nor single quotes here. Might be causing an issue.
Also, I assume 1 is an integer so no need to quote that.
The Fix: PDO OF COURSE!
$configs = include("config.php");
$dsn = 'mysql:dbname='.$configs['SQL-Database'].';host='.$configs['SQL-Host'].'';
$user = $configs['SQL-User'];
$password = $configs['SQL-Pass'];
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$st = $db->prepare('SELECT UniqueID FROM tickets WHERE notified=0');
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $d){
echo $d['UniqueID'] . "<br/>";
$id = $d['UniqueID'];
$st = $db->prepare("UPDATE tickets SET notified=1 WHERE UniqueID=$id");
$st->execute();
}
$sql = "UPDATE tickets SET notified='1' WHERE UniqueID='$Unique'";
The error I think it's here. You can't use $Unique between single quotes (although you already are between double quotes).
Try to fixing this replacing the line with:
$sql = "UPDATE tickets SET `notified`='1' WHERE `UniqueID`=$Unique";
Firstly in your query you are passing a string in: ...WHERE "UniqueID"="$Unique" because of the quotes around your php variable. So your query looks like this: WHERE UniqueID = "10". Not a big deal but generally if your looking up a number your should drop the quotes.
And i suspect something is causing your query in the loop to fail, so add something to check for errors:
if(!$queryResult){
echo $con->error;
}
Run the loop and see if something is causing errors in your query. But really you should get rid of most of the backticks you have in your queries.
Related
I know this has been asked before but I cant seem to fix my code.
What I need is to run some php code to query mysql using mysqli for a select statement to retrieve my bcrypt hashed pass so I can compare the user input with the user hashed password. NOTE: I have not yet added mysql_real_escape_string to my $POST variables.
I've changed this code a thousand times still cant get it.
Ive even copy and pasted to a new file a simple query script using num_row
and printf($row['pass']); used echo etc..... I've used fetch array ive tried almost everything I've been all via php mysql at php.net w3c.com etc etc is my system broke? Does mysqli have a bug ? and no i dont want to switch to PDO I wont stop til this is fixed and when there is no longer sql injection vulns
Heres my code:
<?php
$conn = new mysqli('localhost', 'root', '', 'social');
if (mysqli_connect_errno())
{
exit("connection failed" . mysqli_connect_error());
}
else
{
echo "connection established";
}
$db=mysqli_select_db( $conn,'social');
if ($_POST && isset($_POST['submit'], $_POST['password'], $_POST['email']))
{
$pass = ($_POST["password"]);
$email =($_POST["email"]);
$bcrypt = password_hash($pass, PASSWORD_BCRYPT, array('cost' => 12));
}
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$fetcher = mysqli_fetch_assoc($query);
echo $fetcher;
if ($conn->query($fetcher) === TRUE)
{
echo "query has gone through now we need to store the hash<br /> for comparison";
}
else
{
echo "error did not retrieve hash info";
}
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$fetcher = mysqli_fetch_assoc($query);
Before you can fetch records from the result of the query, you need to actually perform the query. Your code should be
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$result = $conn->query($query); // This is where the query is executed
$fetcher = $result->fetch_assoc();
Two more points.
First, you don't need to call mysqli_select_db; you've already selected the database in your constructor call, so you only need to call mysqli_select_db if you want to access a different database.
Second, instead of calling mysql_real_escape_string you should look into using prepared statements, which do the same thing and also correctly handle type-matching and quoting.
Try fetching the value from database after executing the query
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$executedQuery = $conn->query($query);
if($executedQuery) {
$fetcher = mysqli_fetch_assoc($executedQuery);
echo "query has gone through ---------";
} else {
echo "error did not retrieve hash info";
}
$query = "SELECT pass FROM social WHERE id = 11"; // took the (``) out of the query and added this im assuming the value is stored in the $row variable and I may be able to use $row with the user input to verify hash via bcrypt!!!
$result = $conn->query($query);
while($row = mysqli_fetch_array($result))
{
echo $row['pass'];
echo "<br />";
}
-I want to get the Id of user so I can show a welcome message in his profile but I cant seem to return the id. Maybe it is a problem in the query but when I run the code it only shows: "Error:" so I cant seem to find what is wrong.
-I have tried different sintaxes for the queries and they also work when testing them in phpmyadmin with concrete values.
-"Emri" is firstname in my language.
My db connection:
$dbc = mysqli_connect('127.0.0.1', 'root', '', 'oms_db');
my fuctions in a file fuctions.php:
ini_set ("display_errors", "1");
error_reporting(E_ALL);
include('dbc.php');
function getId($dbc, $username)
{
$query = "SELECT id FROM user WHERE username='.$username.'";
$q = mysqli_query($dbc, $query);
if($r = mysqli_fetch_assoc($q)){
return $r[id];
}
else {
echo "Error: ".mysqli_error($dbc);
}
}
function getData($dbc, $id, $data)
{
$q = "SELECT * FROM user WHERE id='.$id.'";
$r = mysqli_query($dbc, $q);
$array = mysqli_fetch_assoc($r);
echo $array[$data];
}
How I called the fuctions:
if(isset($_SESSION['username'])) {
if(!isset($_GET['id'])){
$userId = getId($dbc, $_SESSION['username']);
}
echo "Welcome to profile, ".getData($dbc, $userId, 'emri');
I have read 10 or more posts in stakoverflow but haven't found a solution. I think it is a problem with phpmyadmin or maybe queries dont work within a function.
The problem here is with the quotes and concatenates in
WHERE username='.$username.'";
either remove the dots
WHERE username='$username'";
or add double quotes
WHERE username='".$username."'";
since we are dealing with strings
https://dev.mysql.com/doc/refman/5.5/en/string-literals.html
Look into using prepared statements also:
https://en.wikipedia.org/wiki/Prepared_statement
So Im trying to delete a record from a table using php and sql and check whether it has been deleted using a rowcount() function in an if statement.
Im having problems on both fronts...
<?php
echo $_GET['id'];
if (isset($_GET['id'])) {
$trainingID = $_GET['id'];
}
else {
die('There was a problem with the ID given.');
}
// include the connection file
require_once('./includes/connection.inc.php');
$conn = dbConnect();
// prepare SQL statement
$sql = 'DELETE FROM `trainingCourses` WHERE `trainingID` = "$trainingID"';
$stmt = $conn->prepare($sql);
try {
$stmt->execute();
echo "deleted";
echo $stmt->rowcount();
//check number of rows affected by previous insert
if ($stmt->rowCount() == 1) {
$success = "$trainingID has been removed from the database.";
}
}
catch(PDOException $e){
echo $e;
echo 'Sorry, there was a problem with the database.';
}
?>
I currently get 3 things outputted from my echo's throughout my code, firstly i get T0001, which is the primary key of the record i want to delete from another page. Secondly i get "deleted" which is from an echo within my 'try' statement but the record doesn't actually delete from the database. This is backed up from the rowcount() function which outputs 0.
I can't seem to get this working and im sure it should be simple and is something i am just overlooking!
Will the try method default to the catch if the "if" statement in it fails? As im also unsure what should be output from a rowcount() when a row has been deleted?
Any help you could offer would be really helpful! Thanks!
echo'ing this line
$sql = 'DELETE FROM `trainingCourses` WHERE `trainingID` = "$trainingID"';
will treat $trainingID as string and not variable.
$sql = "DELETE FROM `trainingCourses` WHERE `trainingID` = '$trainingID'";
will do the work BUT its not safe (sql injections). You should use PDO to bind varaibles like this
$sth = $dbh->prepare("DELETE FROM `trainingCourses` WHERE `trainingID` = :id");
$sth->bindParam(":id",$trainingID);
$sth->execute();
Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);
I am trying to make it so I can restrict the "staff panel" to users with there "member_level" at "3" so others get redirected to the account_page.php but I am currently getting a error which only cropped up 1hr ago, this came out of nowhere I didn't change anything it just came up.
This is the code for the staff panel:
<?php
ob_start();
mysql_connect('localhost', 'u1908470_cms', 'BeingX1309X')or die("Error: ".mysqlerror());
mysql_select_db('u1908470_cms');
$query1 = mysql_query("SELECT 'member_level' FROM `users` WHERE `username` = '" . mysql_real_escape_string ($_SESSION['user']['username'])."'");
$query2 = mysql_result($query1,0,'member_level') or die(mysql_error());
switch ($query2)
{
case 3:
{
echo "<p>Now Logged into Staff Panel!</p>";
}
break;
case 2:
{
header("location: http://www.cookiedenied.com/account_page.php");
}
break;
case 1:
{
header("location: http://www.cookiedenied.com/account_page.php");
}
break;
}
?>
Escape field and table names properly
Instead of
SELECT 'member_level', ....
...please use...
SELECT `member_level`, ....
Validate your Query.
Rewrite your code like this:
$SQL = "SELECT `member_level`
FROM `users`
WHERE `username` = '"
. mysql_real_escape_string($_SESSION['user']['username'])
. "'";
$MyQ = mysql_query($SQL);
$MyR = mysql_result($MyQ,0,'member_level') or die(mysql_error());
...and var_dump($SQL); to see if your statement is valid. Check it while executing it with another MySQL Tool (Workbench, phpMyAdmin, SQLyog or whatever) to see if it generates any results. Maybe the $_SESSION variable isn't set up properly or something similar, you'll find out this way.
Please use MySQLi or PDO instead.
From the manual:
Use of the mysql extension is discouraged. Instead, the MySQLi or
PDO_MySQL extension should be used.
Reformat your switch-Block.
Not related to your question, but your switch-Block looks overly complicated to archieve something way easier. Try this:
switch ($query2) {
case 3:
echo "<p>Now Logged into Staff Panel!</p>";
break;
default:
header("location: http://www.cookiedenied.com/account_page.php");
}
try this :
$R = mysql_fetch_assoc($query1);
$query2 = $R["member_level"]
But may be you should check that your query returns at least 1 row.
Why you have ' around table name in your query, it might be back tick
$query1 = mysql_query("SELECT `member_level` FROM `users` WHERE `username` = '" . mysql_real_escape_string ($_SESSION['user']['username'])."'") or die(mysql_error());
Use or die(mysql_error()); to check error in your query.
First of all try to avoid mysql_query. This is getting obsolete and make a habit of using PDO.
In your query you have surrounded the tablename with quotes. Remove the quotes and try.
Change the code. And replace with the below code.
<?php
ob_start();
try {
$pdo = new PDO('mysql:host=localhost;dbname=u1908470_cms', 'u1908470_cms','BeingX1309X');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$username = $_SESSION['user']['username'];
$statement = $pdo->prepare("select `member_level` from `users` where username = :username");
$statement->execute(array(':username' => $username));
$row = $statement->fetch();
$member_level = $row['member_level'];
switch ($member_level)
{
case 3: {
echo "<p>Now Logged into Staff Panel!</p>";
break;
}
default:{
header("location: http://www.cookiedenied.com/account_page.php");
break;
}
}
You can actually remove the switch statement and just put if-else condition.
if($member_level == 3) {
echo "<p>Now Logged into Staff Panel!</p>";
}else{
header("location: http://www.cookiedenied.com/account_page.php");
}
?>