Overwritte data in postgresql table php - php

The data present in the postgresql table isn't update any more. I want to overwrite the data. When I just use insert into, new data is added but the old data remains. I tried to use update but then I get errors. I would like to update all records. I think it's probably something with the syntax. But I can't find the problem.
Code
$dbname = "dbtest";
$host = "localhost";
$username = "postgres";
$password = "pasword";
$dbh = new PDO("pgsql:dbname=$dbname; host=$host", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$c = array("Human","Mouse","Rat","Hamster","SV40");
$b = array("Human HBO gene", "Mouse BB gene", "Human CCB gene", "SV40 TP gene", "Hamster TP53 gene");
$count=0;
foreach($c as $key => $d){
$e =$b[$key];
$name = $count++;
if (strpos($e, $d) !== FALSE) {
$match = $d;
$specie = $d;
$specie = str_replace("Human","Homo Sapiens",$specie);
$specie = str_replace("Mouse","Mus Musculus",$specie);
$specie = str_replace("Rat","Rattus norvegicus",$specie);
$Specie = str_replace("Hamster", "Mesocricetus Auratus",$specie);
$specie = str_replace("SV40","Simian virus 40",$specie);
}else{
$match = "0";
$specie = "0";
}
echo $match. " ". $specie. " ";
$var_id = $name;
$var_match = $match;
$var_full_name = $specie;
#$sql = "INSERT INTO species (id,match,full_name) VALUES ('".$var_id."','".$var_match ."','".$var_full_name."')";
$sql = "UPDATE species SET id = '".$var_id."', match = '".$var_match ."', full_name='".$var_full_name."'";
if ($dbh->query($sql)) {
echo "New Record Inserted Successfully!<br \>\n";
}else{
echo "Data not successfully Inserted.<br \>\n";
}
}
The error I get:
Fatal error: Uncaught PDOException: SQLSTATE[42601]: Syntax error: 7 ERROR: > syntax error at or near "Sapiens" LINE 1: ...species SET id = '0', match = Human, full_name=Homo Sapiens' ^ in /var/www/html/test/Insert.php:59 Stack trace: #0 /var/www/html/test/Insert.php(59): PDO->query('UPDATE species ...') #1 {main} thrown in /var/www/html/test/Insert.php on line 59

You should use a select query to determine if the value is new or old. If old update data, else insert data.
FUNCTION
function execute_query($query,$dbh){
if ($dbh->query($query)) {
return "New Record Inserted Successfully!<br \>\n";
}else{
return "Data not successfully Inserted.<br \>\n";
}
}
SELECT
$query = 'SELECT * FROM tbl '. 'WHERE "test1" = '.
"'".$var_test."'" . 'AND "test2" = '.
"'".$var_test2."'";
$stmt = $dbh->prepare($query);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$outcome = $stmt->fetch();
UPDATE
if ($outcome !== false){
$sql = "UPDATE tbl SET test1 = '".$var_test1."', test2 = '".$var_test2."',
test3 = '".$var_test3."'
"WHERE id = '".$var_id."' ";
execute_query($sql,$dbh);
INSERT
}else{
$sql = "INSERT INTO genes
(id,test1,test2,test3)
VALUES ('".$var_id."','".$var_test1 ."','".$var_test2."','".$var_test3."')";
execute_query($sql,$dbh);
}

When I use the following syntax, the error is gone. This query needs to be used to update.
$sql = "UPDATE species SET match ='".$var_match ."', full_name='".$var_full_name."' WHERE id = '".$var_id."' ";

Related

About the error of PHP-Column count doesn't match value count at row 1

I'm new about the PHP. I create a login form and after I fill up all the input fields. I clicked "SUBMIT" and then it says.. "Column count doesn't match value count at row 1". anybody help me about this. I'm stack with this almost 1 week.. here is my code. and my db connection.
<?php
$connection = mysqli_connect("localhost","root","","db_violation");
function DBCon(){
try{
$connection = new PDO("mysql:host=localhost;port=3306;dbname=db_violation;","root","");
return $connection;
}catch(PDOException $e){echo "Connection failed: ".$e->getMessage();}
}function DBDiscon(){return $connection = null;}
?>
<?php
include '../../PROCESS/dbconnect/dbconnect.php';
$datauserssystems = json_decode(file_get_contents("php://input"));
$user_firstname = mysqli_real_escape_string($connection, $datauserssystems->user_fname);
$user_middlename = mysqli_real_escape_string($connection, $datauserssystems->user_mname);
$user_lastname = mysqli_real_escape_string($connection, $datauserssystems->user_lname);
$user_address = mysqli_real_escape_string($connection, $datauserssystems->user_address);
$user_positionss = mysqli_real_escape_string($connection, $datauserssystems->user_positions);
$user_age = mysqli_real_escape_string($connection, $datauserssystems->user_age);
$user_username = mysqli_real_escape_string($connection, $datauserssystems->user_uname);
$user_userpass = mysqli_real_escape_string($connection, $datauserssystems->user_pwd);
$tableRows = DBCon()->prepare("SELECT COUNT (*) AS row FROM sb_account");
$tableRows->execute();
$count = $tableRows->fetch();
$count = ($count["row"]+1);
$gain ="SbAdmin";
$encrpt = md5($gain.$user_userpass);
$security = DBCon()->prepare("INSERT INTO sb_account_security VALUES('".$count."','".$encrpt."','".$user_userpass."')")->execute();
$sbuserssssquery = mysqli_query($connection, "SELECT * FROM sb_account WHERE sb_username='$user_username'");
$sbuserssssarray = mysqli_fetch_array($sbuserssssquery);
$sbuserssss = $sbuserssssarray['sb_username'];
if($sbuserssss == $user_username) {
echo "sbtwice";
die();
}
else {
mysqli_query($connection, "INSERT INTO sb_account (sb_firstname,sb_middlename,sb_lastname,sb_fullname,sb_address,sb_position,sb_age,sb_username,sb_password) VALUES ('$user_firstname','$user_middlename','$user_lastname','$user_address','$user_positionss','$user_age','$user_username','$encrpt')");
if(mysqli_affected_rows($connection) > 0) {
echo "AddUserSystem";
die();
}
else {
echo mysqli_error($connection);
die();
}
}
?>
Your mysql insert query has issue:
INSERT INTO sb_account
(sb_firstname,
sb_middlename,
sb_lastname,
sb_fullname,
sb_address,
sb_position,
sb_age,
sb_username,
sb_password)
VALUES ('$user_firstname',
'$user_middlename',
'$user_lastname',
'$user_address',
'$user_positionss',
'$user_age',
'$user_username',
'$encrpt');
Here you have 9 columns but are supplying 8 values. You are not passing value for sb_fullname column.

change data from database using php

I want to change data from a database but I keep getting errors and I just cannot find the mistake I made..
Here's the code:
if(isset($_POST['id'])) {
if(is_numeric($_POST['id'])) {
$change = pg_query($db, "SELECT * FROM azubi3 WHERE id = ".$_POST['id']."");
echo $change;
if($auto == "") {
$auto = "false";
}
else { $auto = "true"; }
$change = pg_query($db, "UPDATE azubi3 SET vorname = '".$_POST['prename']."', nachname = '".$_POST['name']."', auto = ".$auto.", auto_id = ".$_POST['auto_id'].", schuh_id = ".$_POST['schuh_id']." WHERE id = ".$_POST['id']."");
}
else { echo "ID muss eine Zahl sein!"; }
}
And that's the error i get:
Warning: pg_query(): Query failed: ERROR: syntax error at or near "," LINE 1: ...achname = 'Mustermüller', auto = false, auto_id = , schuh_id... ^ in /srv/www/htdocs/azubi2/test3.php on line 82
First thing your sql is vulenrable to injection, you should correct it.
For the sake of your question :
false is a reserved keyword, please use string around it:
$change = pg_query($db, "UPDATE azubi3 SET vorname = '".$_POST['prename']."', nachname = '".$_POST['name']."', auto = '".$auto."', auto_id = ".$_POST['auto_id'].", schuh_id = ".$_POST['schuh_id']." WHERE id = ".$_POST['id']."");

php - Call to a member function fetch_assoc() on a non-object

Table Structure:
user table:
id:int
user:varchar
hash:varchar
realm:int
Game Table:
ID:int:auto
Game:varchar
Password:varchar
Difficulty:tinytext
Realm:tinytext
Empty:int
timestamp:int
Player Table:
ID:Int
GameID:INT
Name:varchar
timestamp:int
When im trying to fetch_assoc() i'm getting error:
Call to a member function fetch_assoc() on a non-object
function RequestToRemove($Hash, $timestamp)
{
include "conf.php";
$conn = new mysqli($serverip, $username, $password, $dbname, $Port);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$hash = mysqli_escape_string($conn, $Hash);
$UserQuerry = "SELECT * from User where hash = '$hash'";
$UserResult = $conn->query($UserQuerry);
if (!$UserResult) {
echo "hash not found: ".$hash;
}
if ($UserResult->num_rows > 0)
{
while($UserRow = $resulti->fetch_assoc())
{
$PlayerQuerry = "SELECT * from Players where ID = '".$UserRow['id']."'";
$PlayerResult = $conn->query($PlayerQuerry);
while($PlayerRow = $PlayerResult->fetch_assoc())
{
$gameID = $PlayerRow['GameID'];
$gameQuerry = "SELECT * from games where ID = '$gameID'";
$gameResult = $conn->query($gameQuerry);
if ($gameResult->num_rows > 0)
{
while($GameRow = $gameResult->fetch_assoc())
{
if((int)$GameRow['timestamp'] <= ($timestamp - 30) && (int)$GameRow['Empty'] == 1)
{
$gameDeleteQuerry = "DELETE FROM games where id = '".$gameID."'";
$conn->query($gameDeleteQuerry);
echo "Game Updated";
}
}
$playerDeleteQuerry = "DELETE FROM Players where id = '$gameID'";
$gamesUpdateQuerry = "UPDATE games SET timestamp='$timestamp' where ID = '$gameID'";
$gamesUpdateResult = $conn->query($gamesUpdateQuerry);
if (!$gamesUpdateResult) {
echo "Can't UPDATE game! ID: $gameID Error: ". $conn->error;
return;
}
$conn->query($playerDeleteQuerry);
$PlayerQuerry = "SELECT * from players where GameID = '$gameID'";
$PlayerResult = $conn->query($PlayerQuerry);
if (!$PlayerResult) {
echo "Can't get players! Error: " . $conn->Error;
return;
}
if ($PlayerResult->num_rows <= 0) {
$gameUpdateEmptyQuerry = "UPDATE games SET Empty='1' where GameID = '".$gameID."'";
$conn->query($gameUpdateEmptyQuerry);
}
} else {
echo "0 results";
}
}
}
}
$conn->close();
}
but when im running
SELECT * from User where hash = 'ae3cb232b5e489050bfed7ed984eb04c'
in HeidiSQL
i will get one row in response but i can't still fetch_assoc() in php
Reason for edit: Show full function, requested
you are reassigning a different value to $resulti within the loop:
$sqll = "DELETE FROM Players where id = '$gameID'";
$sqlu = "UPDATE games SET timestamp='$timestamp' where ID = '$gameID'";
$resulti = $conn->query($sqlu);
the mysqli::query() function is tricky, it can return different type of return values - an update statement returns either true or false, whereas a select statement returns a mysqli_result or false.
(and yes, it may help to name the variables a bit more descriptive ;) )

Undefined variable while fetching data from mysqli

I'm new to php n I'm trying to make a phone to timezone converter.
I'm getting the error undefined variable '$result' on line 49
How do I resolve it.
Also if you can find out any other mistakes I've made
Please chck for errors I'm making
Phone number:
<button type="submit" name="submit" action="submit">
Submit
</button>
</form>
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$ccode=$_POST["phone"];
// Create connection
$db = new mysqli($servername, $username, $password);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$pattern = '/^\(?[\d]{1,4}\)?( |-)?/';
if(preg_match($pattern, $ccode, $matches))
{
$code = $matches[0];
} else $code = substr($ccode, 0, 4);
$q = "SELECT nicename FROM country.country WHERE phonecode=$code";
if($query = $db->query($q))
{
$record = $query->fetch_assoc();
} else echo "<br/>NO RECORD";
echo '<pre>';print_r($record);
if (empty($_POST["phone"]))
{
echo "<p>Please write a Phone Number!</p>";
}
$abb = "SELECT zone_id FROM zone INNER JOIN country on country.country_code = zone.country_code
WHERE country.country_name = " . $record['nicename'];
if($query = $db->query($abb))
{
$result = $query->fetch_assoc();
} else echo "<br/>NO RECORD";
echo '<pre>';print_r($result);
?>
</body>
Thanks for the help!
I believe this way it will works. I'm not sure about $code, if he contains the right information, you can check that by echo'ing the $code.
if(preg_match($pattern, $ccode, $matches))
{
$code = $matches[0];
} else { $code = substr($ccode, 0, 4); }
$q = "SELECT nicename FROM country WHERE phonecode=$code";
if($query = $db->query($q))
{
$record = $query->fetch_assoc();
echo '<pre>';
print_r($record);
} else { echo "<br/>NO RECORD"; }
$abb = "SELECT zone_id FROM zone INNER JOIN country on country.country_code = zone.country_code
WHERE country.country_name = '" . $record['nicename'] . "'";
if($query = $db->query($abb))
{
$result = $query->fetch_assoc();
echo '<pre>';
print_r($result);
//Here $result will exist!
} else { echo "<br/>NO RECORD"; }
// You had your $result here, and here, the result may not exist,
// depending if the query succeeded or not.
// Same counts for the query above.
There were 2 problems as far as I can tell.
1 was that you tried to print $record, while $record may not have existed, and the same counts for $result.
2 was the zone-query, if you check if a column/field equals a certain string, then make sure the string has quotes around itself. So country_name='something'. You didn't have these quotes around $record['nicename'], so whatever came out of $record['nicename'], he thought it was a column/field, but not a value to check upon.

Do not update with empty vars on UPDATE statement

I am trying to run an sql update but i dont want to update when the post vars that are empty.
Code that i run is :
require '../includes/db.php';
$settings_owner = ( isset($_POST[wb_owner_field]) ? $_POST[wb_owner_field] : false );
$settings_title = ( isset($_POST[wb_title_field]) ? $_POST[wb_title_field] : false );
$settings_description = ( isset($_POST[wb_descr_field]) ? $_POST[wb_descr_field] : false );
$settings_keywords = ( isset($_POST[wb_keywd_field]) ? $_POST[wb_keywd_field] : false );
$settings_id = ( isset($_POST[wb_id]) ? $_POST[wb_id] : false );
try {
$sql = "UPDATE Website SET website_owner = '$settings_owner', website_title = '$settings_title', website_description = '$settings_description', website_keywords = '$settings_keywords' WHERE _ID = '$settings_id' ";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
One way is to test the value in the UPDATE statement:
$sql = "UPDATE Website
SET website_owner = IF('$settings_owner' = '', website_owner, '$settings_owner'),
website_title = IF('$settings_title' = '', website_title, '$settings_title'),
website_description = IF('$settings_description' = '', website_description, '$settings_description'),
website_keywords = IF('$settings_keywords' = '', website_keywords, '$settings_keywords')
WHERE _ID = '$settings_id' ";
Another way is to build the UPDATE statement dynamically.
$sets = array();
if ($settings_owner != '') {
$sets[] = "website_owner = '$settings_owner'";
}
if ($settings_title != '') {
$sets[] = "website_title = '$settings_title'";
}
...
if (!empty($sets)) {
$sql = "UPDATE Website SET " . implode(', ', $sets) . " WHERE _ID = '$settings_id'";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
I don't do much web programming, and haven't touched php in 10 years, but I work with MySQL daily and would imagine something like this would work:
UPDATE Website
SET website_owner = IF('$settings_owner'='', website_owner, '$settings_owner')
, website_title = IF('$settings_title'='',website_title, '$settings_title')
, website_description = IF('$settings_description'='',website_description, '$settings_description')
, website_keywords = IF('$settings_keywords'='',website_keywords, '$settings_keywords')
WHERE _ID = '$settings_id'
;

Categories