The database doesn't get updated for some strange reason, I can get the correct data (I checked it), but the database does not get updated when I click submit. Can you anyone check if there is anything missing?
NB: the "----" are just for security reasons!
<?php
$host = "sql308.-----.com";
$dbUsername = "----_3041----";
$dbPassword = "-----------";
$dbName = "----_3041----_phpmysqli";
$conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($conn-> connect_error) {
die("Connection échouée!".$conn-> connect_error);
}
$rn = $_GET['rn'];
$dt = $_GET['dt'];
$to = $_GET['to'];
$rk = $_GET['rk'];
if(isset($_POST['edit'])) {
$rn = $_POST['rn'];
$dt = $_POST['date'];
$to = $_POST["total"];
$rk = $_POST['remarques'];
$sql = "UPDATE `datab1` SET
`date` = '$dt',
`total` = '$to',
`remarques` = '$rk'
WHERE `datab1`.`id` = '$rn'";
$result = mysqli_query($conn, $sql);
if($result == 1) {
header('location:table.php');
}
else {
die(mysqli_error($conn));
}
}
?>
Most probably the update is executed without finding a match for the where condition.
Just before
if(isset($_POST['edit'])) {
add the following code at line 18
echo "<p>GET: "; var_dump($_GET); echo "<p>POST: "; var_dump($_POST); echo "<p>";
and inspect the values.
Also before
$result = mysqli_query($conn, $sql);
at line 30, please add
echo "<br>$sql<br>"; exit();
And if you could not solve after reviewing both the outputs, please post the same here.
Thank you #Natarajan N Napoleon for the helpful trick, the outputs are correct in both GET and POST as it's shown here:
GET: array(9) { ["rn"]=> string(2) "21" ["dt"]=> string(10) "07-12-2021" ["rk"]=> string(5) "walou" ["to"]=> string(4) "1250" }
POST: array(9) { ["date"]=> string(10) "07-12-2021" ["total"]=> string(4) "1800" ["remarques"]=> string(5) "done" ["edit"]=> string(8) "Modifier" }
the SQL Query is the one making troubles, this is what I get:
UPDATE `datab1` SET `date` = '07-12-2021', `total` = '1800', `remarques` = 'done' WHERE id = ''
I was assigning a null to my "rn" which caused this error, I had to pass the value of "rn" directly to my query without no modification.
Related
I'm using this to select data from mysql in php
<?php
error_reporting(E_ALL);
$servername = "localhost";
$username = "******";
$password = "******";
$database = "*******";
// Create connection
$conn2 = new mysqli($servername, $username, $password, $database);
$stmt = $conn2->prepare('SELECT id, title, views from `blog_main`');
$stmt->execute();
var_dump($stmt);
$result = $stmt->get_result();
while($r=$result->fetch_assoc())
{
echo "id: " . $r["id"]. " - Name: " . $r["title"]. " " . $r["views"]. "<br>";
}
$conn->close();
?>
However no result is shown, but if I run this query on phpmyadmin interface it returns rows.
This code worked fine on localhost but when I shifted it to godaddy's server, I'm facing this problem only in prepared statement.
When I'm using normal query method it displays rows, only prepared statements are not working.
This is the value of var dump:
object(mysqli_stmt)#2 (10) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(0) ["field_count"]=> int(3) ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
Is there any kind of extension I need to enable or what might be the problem?
here is my answer for your question,
create file db.php
$dbInfo = array(
'host' => "localhost",
'user' => "******",
'pass' => "******",
'dbname' => "******"
);
create dbcon.php
class database{
protected $databaseLink;
function __construct(){
include "db.php";
$this->database = $dbInfo['host'];
$this->mysql_user = $dbInfo['user'];
$this->mysql_pass = $dbInfo['pass'];
$this->databaseName = $dbInfo['dbname'];
$this->openConnection();
return $this->get_link();
}
function openConnection(){
$this->databaseLink = mysqli_connect($this->database, $this->mysql_user, $this->mysql_pass, $this->databaseName);
}
function get_link(){
return $this->databaseLink;
}
}
create func.php
include "dbcon.php";
function selectData(){
$db = new database();
$selectQuery = "SELECT id, title, views FROM blog_main";
$selectQuery = mysqli_query($db->get_link(), $selectQuery) or die(mysqli_error());
while($r = mysqli_fetch_assoc($selectQuery)) {
$rows[] = $r;
}
return $result = json_encode(($rows));
mysqli_close($db->get_link());
}
and in for example index.php you can get data from which SQL return
include "func.php";
$data = selectData();
$dataJson = json_decode($data, TRUE);
foreach ($dataJson as $key => $value) {
echo "id: " . $value['id']. " - Name: " . $value['title']. " " . $value['views']. "<br>";
}
good luck
Seems like it was the disable driver issue. I enabled the stmt_mysqli driver and it worked.
I am getting return values that do not exist in my current database. Even if i change my query the return array stays the same but missing values. How can this be what did i do wrong?
My MYSQL server version is 10.0.22 and this server gives me the correct result.
So the issue must be in PHP.
My code:
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Result:
array(1) {
[1]=> array(9) {
["UID"]=> string(1) "1"
["CreationTimestamp"]=> NULL
["UpdateTimestamp"]=> NULL
["ProcessState"]=> NULL
}
}
Solution:
I have found this code somewhere in my program. The program used the same name ass mine. This function turns the MYSQL result into a array. This happens between the result view and my script. This was done to make the result readable.
parent::processUpdatedAfter($date);
Function:
public function processUpdatedAfter($date)
{
$result = parent::processUpdatedAfter($date);
$array = Array();
if($result != false)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$array[$row["UID"]]["UID"] = $row["UID"];
$array[$row["UID"]]["CreationTimestamp"] = $row["CreationTimestamp"];
$array[$row["UID"]]["UpdateTimestamp"] = $row["UpdateTimestamp"];
$array[$row["UID"]]["ProcessState"] = $row["ProcessState"];
}
return $array;
}
return false;
}
I edited this and my script works fine now thanks for all the help.
Note that, var_dump($result); will only return the resource not data.
You need to mysql_fetch_* for getting records.
Example with MYSQLi Object Oriented:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['UID'];
}
}
else
{
echo "No record found";
}
$conn->close();
?>
Side Note: i suggest you to use mysqli_* or PDO because mysql_* is deprecated and closed in PHP 7.
You are var_dumping a database resource handle and not the data you queried
You must use some sort of fetching process to actually retrieve that data generated by your query.
$ts = '2016-09-20 08:56:43';
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > '$ts'";
$result = mysql_query($select_query, $link_identifier);
// did the query work or is there an error in it
if ( !$result ) {
// query failed, better look at the error message
echo mysql_error($link_identifier);
exit;
}
// test we have some results
echo 'Query Produced ' . mysql_num_rows($result) . '<br>';
// in a while loop if more than one row might be returned
while( $row = mysql_fetch_assoc($result) ) {
echo $row['UID'] . '<br>';
}
However I have to mention Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
$select_query = "SELECT `UID` FROM `process_state ` WHERE `UpdateTimestamp` > \"[given time]\" ORDER BY UID DESC ";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Try this hope it will works
I am making an application in which I pull data from an SQL database. My php code echos json data but its not well formed. My current output does not have a name of the array of results, and I would like it to - I have provided a link to a picture of how I would like the output to look.
Any help would be greatly appreciated.
<?php
// database settings
$db_username = "****";
$db_password = "****";
$db_name = "****";
$db_host = "****";
//open connection to mysql db
$connection = mysqli_connect("$db_host","$db_username","$db_password","$db_name") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from markers";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
$data = array($emparray);
echo json_encode($data);
//close the db connection
mysqli_close($connection);
?>
Final JSON
Current Output
What if you replace line
$data = array($emparray);
with
$data = array('markers' => $emparray);
?
It should output something like
JSON : {"markers":[{"id":1,"lorem":"ipsum"},{"id":2,"lorem":"dolor"}]}
php > var_dump($test);
array(1) {
["markers"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
int(1)
["lorem"]=>
string(5) "ipsum"
}
[1]=>
array(2) {
["id"]=>
int(2)
["lorem"]=>
string(5) "dolor"
}
}
}
I have a class which works fine with php 5.3 (XAMPP 1.7.3, windows 7) but doesn't work in my server(php 5.2.17 - Safe mode On):
<?php
class MYSQL_DB {
var $connection;
function MYSQL_DB() {
$this->connection = mysql_connect(S, U, P) or die('Can\'t connect to MySQL server.');
mysql_select_db(DB, $this->connection) or die(mysql_error());
}
function getJobs($wid) {
$q = "SELECT * FROM " . TB_PREFIX . "joblist where owner = {$wid} order by ID ASC";
$result = mysql_query($q, $this->connection);
$ret = $this->mysql_fetch_all($result);
mysql_free_result($result);
return $ret;
}
function mysql_fetch_all($result) {
$all = array();
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$all[] = $row;
}
return $all;
}
}
}
$db=new MYSQL_DB();
?>
And in another file, I used getjobs function:
<?php
$tempbJobs=$db->getJobs(1368);
var_dump($tempbJobs);
?>
when I use var_dump right before return $ret; in getjobs function, it shows me correct values, but var_dump($tempbJobs); will print NULL.
P.S: I simplified the code, it works on my localhost but not on production server.
P.S: If I change return $ret; to return 'DUMPED'; , returned value would be string(6) "DUMPED"
var_dump($ret ); output:
array(2) {
[0]=>
array(5) {
["id"]=>
string(5) "10755"
["owner"]=>
string(5) "23626"
["field"]=>
string(1) "6"
["type"]=>
string(1) "2"
["expi"]=>
string(10) "1372144648"
}
[1]=>
array(5) {
["id"]=>
string(5) "10756"
["owner"]=>
string(5) "23626"
["field"]=>
string(1) "5"
["type"]=>
string(1) "2"
["expi"]=>
string(10) "1372144654"
}
}
Based on the fact that you only return $all from the function mysql_fetch_all($result) if $result is true I have to assume that the mysql_query() is returning false.
After the call to
$result = mysql_query($q, $this->connection);
Can you add this
$result = mysql_query($q, $this->connection);
if ( ! $result ) {
echo "ErrorNo: " . mysql_errno() . " Error Message: " . mysql_error();
}
This might help identify what the problem actually is as it has to be a database error of some sort.
Could you check that your constants S, U, P, TB_PREFIX are defined() and they have values.
Also modify your function mysql_fetch_all to return response anyway:
function mysql_fetch_all($result) {
$all = array();
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$all[] = $row;
}
}
return $all;
}
I reviewed all your comments.
In one of your comments you said that return is not working but I think it is working properly because you already said in one of your comments that when you print out the result before return $ret it gives you the correct result.
fact : mysql_fetch_all($result) also returning result.
checkout the sql code : $q = "SELECT * FROM " . TB_PREFIX . "joblist where owner = {$wid} order by ID ASC"; I do not know {$wid} what it is.
Test it
$q = "SELECT * FROM " . TB_PREFIX . "joblist where owner = '$wid' order by ID ASC";
try after defining array for $ret in the function getjobs()
$ret=array(); //try
I know this is a little bit rusty question but yet still interesting. Are you able to found solution on that ?
If same code doesn't work on different server i would have suspected in that case memory limit. Try to increase php memory limit.
And it could be wise to check phpinfo(); on both servers to compare differences.
I got a Bash/PHP script that retrieves records from a table called 'assess_2012' and stores records that need to be written to a table called 'assess_2012_err' in a multidimensional array:
#!/usr/bin/php -q
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$name = "reassess";
$conn = mysqli_connect($host, $user, $pass, $name) OR die ("Could not connect to database: " . mysqli_error($conn) . "\n");
$q = "SELECT su_id, ass_date, ind_d FROM assess_2012";
$r = mysqli_query ($conn, $q);
if ($r) {
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
// Check for errors:
if ($row['ind_d'] == 'Y') {
// Add to the array:
$sql[] = array('su_id' => $row['su_id'], 'err_code' => 1);
}
}
var_dump($sql);
}
else {
// SELECT query failed:
echo "Error: " . mysqli_error($conn) . "\n";
}
?>
The 'var_dump' looks like this (shortened version - the actual query returns hundreds of records):
array(1) {
[0]=>
array(2)
["su_id"]=>
string(1) "5"
["err_code"]=>
int(1)
}
[1]=>
array(2) {
["su_id"]=>
string(4) "1492"
["err_code"]=>
int(1)
}
}
What I can't figure out is how I can use the array to produce a query like this:
INSERT INTO assess_2012_err (su_id, err_code) VALUES (5, 1), (1492, 1)
Use a foreach loop to loop through data as you enter the values into the database.
Like:
foreach($sql as $key=>$value){
foreach($value as $key_p=>$value_p){
//Implement Query here
//R.g
//$key will have 'su_id'
//$value_p will have 1
}
}
You'll be better off doing one by one, like so
foreach($sql as $variables)
{
// Insert here:
INSERT INTO asses_2012_err (su_id, err_code) VALUES ($variables['su_id'], $variables['err_code']);
}
Some important things to bear in mind:
Treat those inputs as user inputs, sanitise them!
Try to use PDO as mysql_* functions are going to be deprecated
Consider a data abstraction layer (so all your queries are hidden away inside nice functions)