Data which is succesfully added in database, doesnt show in database - php

im adding data in databese with php and received "succesful" but when i look into the database the data which is i have just added doesnt show. Here my codes
<?php
require ('db.php');
#$name = $_POST['name'];
#$surname = $_POST['surname'];
#$number = $_POST['number'];
#$mail = $_POST['mail'];
#$note = $_POST['note'];
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if ($sql)
{
echo "Succesful";
}
else
{
echo "error";
}
?>
this is also my db.php codes ;
<?php
$con = mysqli_connect("localhost","root","","customers");
if (mysqli_connect_errno()) {
printf(" Connection error :( %s\n", mysqli_connect_error());
exit();
}
?>
i also have one more question. When i try to add data in databese with mysqli_query() function, it doesnt work. for example;
mysqli_query($con, "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES($name,$surname,$number,$email,$note)");
because of this , i had to use this code,its working now but i have no idea why mysqli_query() function is doesnt work
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if you help me it would be great, thank you.

Put single quote(') in values like this
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ('$name','$surname','$number','$mail','$note')";

You are checking just $sql variable which doesn't provide sql resul, it's just a query.
Try
$result = $con->query($sql);
if($result)
{
echo "Succesful";
}else{
echo "error";
}

More proper way:
$sql = "INSERT INTO `customersinfo`
(`name`,`surname`,`number`,`email`,`notes`) VALUES
('{$name}','{$surname}','{$number}','{$mail}','{$note}')";
$result=$con->query($sql);
if (!$result) {
// Query has failed
}

You checked $sql in if condition which is not right because $sql is always true so that u get the result successful but actually value is not getting inserted in database.
take the result in some variable and used that in if condition.
after that you will get what actual error in your code.

Related

Reading and displaying Values from Sqlite3 Database with PHP

I am writing a application that will read values from an SQlite3 database and display them through webbrowser with PHP. This is new to me and I have tried several things but can't seem to get it to work! The values are listed as REAL in the database, which should be PARAM_STR.
<?php
$db = new SQLite3('/home/pi/ECE522/test.db');
if(!$db) {
echo $db->lastErrorMsg();
} else {
echo "Opened DATABASE!";
$query = $db->prepare('SELECT df1, df2 FROM PLCValues');
$query->bindParm('df1', $df1,PDO::PARAM_STR);
$query->bindParm('df2', $df2,PDO::PARAM_STR);
$query->execute();
var_dump($df1);
var_dump($df2);
echo $df1;
echo $df2;
}
?>
On the webpage I get "Opened DATABASE!" but nothing else?
Thanks for any ideas!
You don't define the $df1 and $df2 before executing the query, that you bind as param at
$query->bindParm('df1', $df1,PDO::PARAM_STR);
$query->bindParm('df2', $df2,PDO::PARAM_STR);
Do you realy need that?
If you just want to select all values in columns 'df1' and 'df2' from PLCValues table, I think you need something like this:
$res = $db->query("SELECT df1, df2 FROM PLCValues");
while (($row = $res->fetchArray(SQLITE3_ASSOC))) {
var_dump($row);
}
For more information see examples from http://php.net/manual/ru/sqlite3stmt.bindparam.php
If you want to select values with certain df1, I think you need something like this:
$stmt = $db->prepare("SELECT df1, df2 FROM PLCValues WHERE df1=:df1");
$stmt->bindParam(':df1', '[WHAT_YOU_WANT_TO_SELECT]', [YOUR_DATA_TYPE]);
$result = $stmt->execute();
var_dump($result->fetchArray());

Issues updating record using mysqli

I want to update/edit my user form, but when I click the "edit" button, I'm not getting the expected results. It should display the new data, but It displays the old data instead.
coding:
<?php
include"errorReporting.php";
include "conn.php";
$conn = connect();
$conndb = connectdb();
$wardID = $_REQUEST["wardID"];
$RequestName = $_REQUEST["RequestName"];
$Department = $_REQUEST["Department"];
$Position = $_REQUEST["Position"];
$Date= $_REQUEST["Date"];
$TypeOfRequest = $_REQUEST["TypeOfRequest"];
$PleaseSpecify = $_REQUEST["PleaseSpecify"];
$DateRequire = $_REQUEST["DateRequire"];
$DateReturn = $_REQUEST["DateReturn"];
mysqli_select_db($conn,"misadmin") or die ($conn->error ."\n");
$query = "select * from requestform";
$result2= $conn->query($query) or die ($conn->error ."\n");
$row_result =mysqli_fetch_assoc($result2);
mysqli_select_db($conn,"misadmin") or die ($conn->error ."\n");
$conn ->query("UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$wardID'",$conn->affected_rows);
$result_update=mysqli_fetch_assoc($result);
header("Location:requestform3.php");
?>
output:
try it:
$conn ->query("UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID=$wardID ");
in where wardID='???' Must retrieve the data before it changes. i mean "4f" not "med".
you can add a textbok in your post form :
<input type="hidden" id="original_wardID" value="<?php echo $wardID?>" />
in your php code add :
$ori_wardID=$_REQUEST['original_wardID'];
then change your sql :
UPDATE requestform SET wardID='$wardID',RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$ori_wardID'
"UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$wardID'"
change to
"UPDATE requestform SET RequestName='".$RequestName."',Department='".$Department."',Position='".$Position."',Date='".$Date."',TypeOfRequest='".$TypeOfRequest."',PleaseSpecify='".$PleaseSpecify."',DateRequire='".$DateRequire."',DateReturn='".$DateReturn."' where wardID=".$wardID
or like this demo code
$db_sql="select id ,uid,regdate from `newtable` where id=?";
$stmt=$mysqli->prepare($db_sql);//
$stmt->bind_param("i",$id);// i int d double s string b blob
$result = $stmt->execute();
but I guess use pdo will be better
You are not using if ($_SERVER['REQUEST_METHOD'] == 'POST'){//save database} or if (isset $_POST['edit']){//save database} for the edit button in order to save data when edit button is clicked.
Plus you are using Date in your UPDATE query (Date =). DATE is also as a native function used in MYSQL, you need to change it. In case you changed it to DateChanged use prepared statement it helps your code to be more readable.
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
$stmt = $conn->prepare("UPDATE requestform SET RequestName=?,
Department=?, Position=?, DateChanged=?, TypeOfRequest=?,
PleaseSpecify=?, DateRequire=?, DateReturn=? WHERE wardID=?");
$stmt->bind_param("sssssssss", $RequestName, $Department,
$Position, $DateChanged, $TypeOfRequest, $PleaseSpecify,
$DateRequire, $wardID);
$stmt->execute();
$stmt->close();
$conn->close();
}
i had found my answer. after i redo back my coding using the old template
here are the code.
<?php
// to connect with the database system
include "errorReporting.php";
include "conn.php";
$conn = connect();
$conndb = connectdb();
$wardID = $_REQUEST["wardID"];
$RequestName = $_REQUEST["RequestName"];
$Department = $_REQUEST["Department"];
$Position = $_REQUEST["Position"];
$DateRequest = $_REQUEST["DateRequest"];
$TypeOfRequest = $_REQUEST["TypeOfRequest"];
$PleaseSpecify = $_REQUEST["PleaseSpecify"];
$DateRequire = $_REQUEST["DateRequire"];
$DateReturn = $_REQUEST["DateReturn"];
mysqli_select_db($conn,"misadmin") or die (mysql_error()."\n");
$query = "select * from requestform" ;
$result = $conn->query($query) or die (mysql_error()."\n".$query);
$row_result=mysqli_fetch_assoc($result);
mysqli_select_db($conn,"misadmin")or die (mysql_error(). "\n");
//to update the data
$update="update requestform SET
RequestName='$RequestName' ,Department='$Department' ,Position='$Position' ,DateRequest='$DateRequest' ,TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify' ,DateRequire='$DateRequire' ,DateReturn='$DateReturn' where wardID='$wardID'";
$rowinsert=$conn->query($update);
header("Location:requestform3.php");
?>
thanks for those who gave the suggestions.I had learnt a lot from you all.

how to store mysql select statement inside php variable using mysqli

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 />";
}

PHP mysqli INSERT does nothing

I looked at a dozen questions and nothing helps. Some give contradictory advice.
I have a simple INSERT INTO query with PHP mysqli. The query and the connection are both ok, and the query actually executes on an older version of xampp. But when I switched to a newer one - nothing! No errors, but, no new data, either.
<?php
$connection = mysqli_connect("localhost", "standard_user", "standard", "liquidity");
if (!$connection) {
die("Error: ".mysqli_connect_errno());
}
$table = "clan";
$username = "someusername";
$ime = "My name";
$query = "INSERT INTO ";
$query.=$table;
$query.=" (username, ime) ";
$query.="VALUES ('".$username."','".$ime."');";
//$query = "INSERT INTO clan (username, ime) VALUES ('someusername', 'My name')";
mysqli_query($connection, $query);
if ($query) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again.");
}
mysqli_close($connection);
?>
This is the query it echoed when I tried it: INSERT INTO clan (username, ime) VALUES ('someusername','My name');
Since every time I reload it prints "Success: My name", I guess it somehow executes. But, no data is saved. I can't figure it out. Any help?
[SOLUTION] The clan table had a foreign key (username) to another table which had no entries, so there was nothing wrong with the query, but a silly overlook actually. Thanks to Deivison Francisco's answer, it was easy to determine the cause of the problem by simply reading an error.
Please use the return value of mysqli_query() to determine the result.
Also think about using prepared statements to mitigate SQL Injections.
$result = mysqli_query($connection, $query);
if ($result) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again. Error message: ".mysqli_error($connection));
}
Alter for:
$query = "INSERT INTO clan (username, ime) VALUES ('someusername', 'My name')";
$return = mysqli_query($connection, $query);
if ($return) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again.");
}
mysqli_close($connection);

Issues with PHP while statement

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.

Categories