I am new in PHP and I'm currently working with a module of Setting an operation wherein I will insert data from a modal into the database. There's no error in terms of getting the data but when I click the button, the "Query failed: INSERT INTO tbl_mobilvis (location, timestart, timeend, mobilnum) VALUES ('vbv','12:09','17:09','4')" always being displayed.
Here's the code for the db class..
var $hostname = "REDACTED";
var $username = "REDACTED";
var $password = "REDACTED";
var $database = "REDACTED";
function select_db() {
$result = mysqli_connect($this->hostname,$this->username,$this->password);
if (!mysqli_select_db( $result, $this->database)) {
echo 'Selection of database: '.$this->database.' failed.';
return false;
}
}
function query($query) {
$result1 = mysqli_connect($this->hostname,$this->username,$this->password);
$result = mysqli_query($result1,$query) or die("Query failed: $query<br><br>" . mysql_error());
return $result;
mysql_free_result($result);
}
function fetch_array($result) {
return mysqli_fetch_array($result);
}
function num_rows($result) {
return mysqli_num_rows($result);
}
function last_insert_id() {
return mysqli_insert_id();
}
function kill() {
mysqli_close();
}
}
?>
and here's the code for inserting the data.
<?php
if (isset($_POST['btnSubmit'])) {
$db = new mysqldb();
$db->select_db();
$result1 = mysqli_connect("REDACTED","REDACTED","REDACTED");
$sql_mobilvis = sprintf("INSERT INTO tbl_mobilvis (location, timestart, timeend, mobilnum) VALUES ('%s','%s','%s','%s')",
mysqli_real_escape_string($result1,$_POST['location']),
mysqli_real_escape_string($result1,$_POST['starttime']),
mysqli_real_escape_string($result1,$_POST['endtime']),
mysqli_real_escape_string($result1,$_POST['mobilnum']));
$result_user = $db->query($sql_mobilvis);
if ($_POST['fields']){
$inserted_mobilvis_id = $db->last_insert_id();
foreach ( $_POST['fields'] as $key=>$value ) {
$sql_enforcer = sprintf("INSERT INTO tbl_mobilenforcer (enforcername) VALUES ('%s')",
mysqli_real_escape_string($result1, $value) );
$result_website = $db->query($sql_enforcer);
$inserted_enforcer_id = $db->last_insert_id();
$sql_mobil_enforcer = sprintf("INSERT INTO tbl_mobil (mobilid, mobilenforcerid) VALUES ('%s','%s')",
mysqli_real_escape_string($result1,$inserted_mobilvis_id),
mysqli_real_escape_string($result1,$inserted_enforcer_id) );
$result_mobil_enforcer= $db->query($sql_mobil_enforcer);
}
} else {
echo "<script>alert('no added enforcers')</script>";
}
echo "<h1>User Added, <strong>" . count($_POST['fields']) . "</strong> enforcers are added!</h1>";
$db->kill();
}
?>
Why I am getting this Query failed?
Related
I found a duplicated row in my table
> image from my table
But in my code, I check if "unique_id" key exists, then update this row, else, create..
I am very noob with sql and I made some functions to make more easy my life... this is my "send_score.php" file
<?php
header('Content-Type: text/plain');
header("Access-Control-Allow-Origin: *");
include "../../functions.php";
$servername = "xxx";
$database = "xxx";
$username = "xxx";
$password = "xxx";
$tabla = "xxx";
$unique_key = $_POST['unique_key'];
$nick = $_POST['nick'];
$puntos = $_POST['puntos'];
$con = sql_connect($servername, $username, $password, $database);
if ( sql_check_row($con,$tabla,"unique_key","'".$unique_key."'") ) {
//if exists, replace
if ( sql_update_row($con,$tabla,"nick",$nick,"unique_key",$unique_key) && sql_update_row($con,$tabla,"sc",$puntos,"unique_key",$unique_key) ) {
echo "OK UPDATE";
exit;
}
else {
echo "BAD UPDATE";
exit;
}
}
else {
//if not exists, create
$arr_key = array("unique_key","nick","sc");
$arr_val = array("'".$unique_key."'","'".$nick."'",$puntos);
if ( sql_insert_row($con,$tabla,$arr_key,$arr_val) ) {
echo "OK INSERT";
exit;
}
else {
echo "BAD INSERT";
exit;
}
}
sql_close($con);
?>
and here is the functions that im using here
function sql_connect($servername, $username, $password, $database) {
return mysqli_connect($servername, $username, $password, $database);
}
function sql_close($con) {
return mysql_close($con);
}
function sql_check_row($con,$table,$key,$value) {
$sql = mysqli_query($con, "SELECT * FROM ".$table." WHERE ".$key." = ".$value);
if( mysqli_num_rows($sql) ) {
return true;
}
else {
return false;
}
}
function sql_update_row($con,$table,$key_set,$value_set,$key_where,$value_where) {
$sql = mysqli_query($con,"UPDATE ".$table." SET ".$key_set." = '".$value_set."' WHERE ".$key_where." = '".$value_where."';");
if ($sql) {
return true;
}
else {
return false;
}
}
function sql_insert_row($con,$table,$key_arr,$value_arr) {
$keys = "(";
for ( $i = 0; $i < sizeof($key_arr); $i++ ){
if ($i != 0) {
$keys .= ",";
}
$keys .= $key_arr[$i];
}
$keys .= ")";
$query = "INSERT INTO ".$table." ".$keys." VALUES (";
for ( $i = 0; $i < sizeof($value_arr); $i++ ){
if ($i != 0) {
$query .= ",";
}
$query .= $value_arr[$i];
}
$query .= ");";
$sql = mysqli_query($con,$query);
if ($sql) {
return true;
}
else {
return false;
}
}
According to me, it shouldn't create a new row because a row already exists with the same "unique_id" and in the image, both rows have exactly the same "unique_id"... why???
A simply strategy here is to write the values of column "unique_key"
in an array and then test if the new value exist with "in_array()".
If the value exists you update. If not you insert a new row:
<?php
$all_unique_ids = array();
$con = sql_connect($servername, $username, $password, $database);
$stmt = $con->prepare("SELECT `unique_key` FROM `".$tabla."`");
$stmt->execute();
foreach ($stmt->get_result() as $row)
{
$all_unique_ids[] = $row['unique_key'];
}
mysqli_close($con);
if(in_array($unique_id, $all_unique_ids))
{
sql_update_row(.....);
}
else
{
sql_insert_row( ......);
}
?>
Your code has a race condition. Two requests to the same page at the same time with the same unique_id will check the database at the same time and both get back the same result. Namely that the given unique_id is not in the database.
Both requests will then each INSERT a row with the same unique_id. This is why databases allow you to give a column a unique constraint.
I'm making a form for some project. The problem is when the user enter their data using the field and then submit, the input not keep in the database.
Also when clicking submit the direct page show blank empty page even the connection test also not showing.
I'm using almost similar code for other project and it work except for this.
below is my code:
<?php
//check connection
require 'config.php';
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
//asas (table name)
$id = $_POST["Sid"]; $ic = $_POST["Sic"];
$name = $_POST["Snp"]; $jant = $_POST["J1"];
$trum = $_POST["Chr"];$tbim = $_POST["Chp"];
$mel = $_POST["Sem"]; $arum = $_POST["Ar"];
$asum = $_POST["As"];
//institusi
$thp = $_POST["T1"]; $uni = $_POST["Sis"];
$bid = $_POST["tpe"];$Aint = $_POST["Ai"];
//industri
$bip = $_POST["bid"];$bik = $_POST["B1"];
$tem = $_POST["te"];$mula = $_POST["tm"];
$tamm = $_POST["tt"]; $res = $_POST["fileToUpload1"];
$tran = $_POST["fileToUpload2"];$keb = $_POST["fileToUpload3"];
$link = mysqli_connect($h,$u,$p,$db);
if('id' != '$Sid'){
$asas = "insert into asas Values ('$id','$ic','$name','$jant','$trum','$tbim','$mel','$arum','$asum')";
$inst = "insert into institusi Values ('$thp','$uni','$bid','$Aint')";
$indr = "insert into industri Values ('$bip','$bik','$tem','$mula','$tamm','$res','$tran','$keb')";
mysqli_query($link,$asas);
mysqli_query($link,$inst);
mysqli_query($link,$indr);
mysqli_close($link);
}
else
{
echo "failed"
}
?>
<b>Register complete</b>
Can anybody tell me what the error or maybe some solution. Thanks
I think you are having problem in insert query, please check this:
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
Write this kind.
thank you
there are few issues with the code like variable id was used without $
and need to use die method with mysqli_query() function to check for
errors, please check below improved codes, it may help you -
<?php
//check connection
require 'config.php';
if (isset($_POST)) {
//asas (table name)
$id = $_POST["Sid"];
$ic = $_POST["Sic"];
$name = $_POST["Snp"];
$jant = $_POST["J1"];
$trum = $_POST["Chr"];
$tbim = $_POST["Chp"];
$mel = $_POST["Sem"];
$arum = $_POST["Ar"];
$asum = $_POST["As"];
//institusi
$thp = $_POST["T1"];
$uni = $_POST["Sis"];
$bid = $_POST["tpe"];
$Aint = $_POST["Ai"];
//industri
$bip = $_POST["bid"];
$bik = $_POST["B1"];
$tem = $_POST["te"];
$mula = $_POST["tm"];
$tamm = $_POST["tt"];
$res = $_POST["fileToUpload1"];
$tran = $_POST["fileToUpload2"];
$keb = $_POST["fileToUpload3"];
}
$link = mysqli_connect($h, $u, $p, $db);
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
// if('id' != '$Sid'){
if ($id != '$Sid') {
$asas = "insert into asas Values
('$id','$ic','$name','$jant','$trum','$tbim','$mel','$arum','$asum')";
$inst = "insert into institusi Values ('$thp','$uni','$bid','$Aint')";
$indr = "insert into industri Values
('$bip','$bik','$tem','$mula','$tamm','$res','$tran','$keb')";
if (mysqli_query($link, $asas)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
if (mysqli_query($link, $inst)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
if (mysqli_query($link, $indr)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
}
mysqli_close($link);
?>
<b>Register complete</b>
just use or die after mysqli_query
mysqli_query($link,$asas)or die ('Unable to execute query. '. mysqli_error($link));
you will get to know what is the actual problem
I have inherited the below code, which creates a web interface for a MySQL database named 'database_name' and defined by the variable $database.
I want to add an additional database to this script, so that the same interface can be created this second database (which is set up in exactly the same way as the first database with the same tables names, etc., but contains different data). Is there a way to make $database a string array which I can loop over for multiple database names?
<?php
class DatabaseInterface {
public $host = "localhost"; //(name or ip address)
public $userName = "aksfhah";
public $passWord = "**********";
public $database = 'database_name';
public $tableData = "measurements";
public $tableMinbins = "minbins";
public $tableHourbins = "hourbins";
public $tableDaybins = "daybins";
public $tableDescriptions = "measurementDescriptions";
public $tableSpecs = "experimentDescriptions";
public $connection;
public function __construct($databaseName = "database_name") {
$this->database = $databaseName;
$this->connect();
}
public function connect($databaseName = null) {
$dbh = mysql_connect($this->host, $this->userName, $this->passWord);
if (is_null($databaseName)) {
mysql_select_db($this->database);
} else {
mysql_select_db($databaseName);
}
$this->connection = $dbh;
return $dbh;
}
public function initializeDatabase() {
$this->createDataTable($this->tableData);
$query = "create table if not exists $this->tableDescriptions (id int auto_increment primary key,type varchar(255),
description varchar(255), experimentname varchar(255), unique Key(description,experimentname)) engine=myisam";
mysql_query($query); //create a table if it does not exist
echo mysql_error(); //report error if one occurred
}
private function createDataTable($tableName) {
$query = "CREATE TABLE IF NOT EXISTS $tableName (
id smallint(5) unsigned NOT NULL,
time datetime NOT NULL,
measurement float DEFAULT NULL,
rebinned tinyint(4) DEFAULT '0',
PRIMARY KEY (id,time),
KEY (rebinned,id)
) ENGINE=MyISAM";
mysql_query($query); //create a table if it does not exist
echo mysql_error(); //report error if one occurred
}
public function insertByDescription($time, $value, $channelDescription, $experimentDescription, $type = "other") {
$sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type);
return $this->insertById($time, $value, $sensorID);
}
public function insertMultipleById($timeArray, $valueArray, $sensorID,$tableName=null) {
if(is_null($tableName)){
$tableName= $this->tableData;
}
if (count($timeArray) == 0)
return 0;
$query = "insert ignore into $tableName (id,time,measurement)
VALUES ";
for ($index = 0; $index < count($timeArray); $index++) {
$timeString = $timeArray[$index]->format("Y-m-d H:i:s");
$value = $valueArray[$index];
$query = $query . "('$sensorID','$timeString','$value'),";
}
$query = substr($query, 0, strlen($query) - 1); //trim final comma
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error();
return false;
} else
return mysql_affected_rows();
}
public function insertMultipleByDescription($timeArray, $valueArray, $channelDescription, $experimentDescription, $type = "other",$tableName=null) {
$sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type);
return $this->insertMultipleById($timeArray, $valueArray, $sensorID,$tableName);
}
public function insertById(DateTime $time, $value, $sensorID) {
$timeString = $time->format("Y-m-d H:i:s");
$query = "insert ignore into $this->tableData (id,time,measurement)
VALUES ('$sensorID','$timeString','$value')";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error();
return false;
} else if (mysql_affected_rows() == 0) {
return false;
} else {
return true;
}
}
public function createIdFromDescription($channelDescription, $experimentDescription, $type) {
$sensorId = $this->getIdFromDescription($channelDescription, $experimentDescription);
if (!$sensorId) {
$query = "insert ignore into $this->tableDescriptions (description,experimentname,type)
VALUES ('$channelDescription','$experimentDescription','$type')";
$result = mysql_query($query);
$sensorId = mysql_insert_id();
}
return $sensorId;
}
public function getIdFromDescription($measurementDescription, $experimentDescription) {
$sensorId = false;
$query = "select id from $this->tableDescriptions where description like '$measurementDescription'
&& experimentname like '$experimentDescription'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$sensorId = $row['id'];
}
return $sensorId;
}
function getDataById($id, $startDate, $endDate, $interval = "") {
$data = array();
$startDateString = $startDate->format("Y-m-d H:i:s");
$endDateString = $endDate->format("Y-m-d H:i:s");
$query = "select time,measurement from $this->tableData where id='$id' && time>='$startDateString' && time <='$endDateString' order by time asc " . $interval = "" ? "" : "group by $interval";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
//$time = new DateTime($row['time']);
$data[] = array($row['time'], $row['measurement'] * 1);
}
return $data;
}
public function getMostRecentData($id, $table) {
$query = "select date(max(time)) as time,measurement from $table where id='$id'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
} elseif (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
return $row;
} else {
return false;
}
}
public function getExperimentList() {
$list = array();
$query = "select distinct experimentname from $this->tableDescriptions";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
$list[] = $row['experimentname'];
}
return $list;
}
public function getChannelList($experimentDescription) {
$list = array();
$query = "select id,description,type from $this->tableDescriptions where experimentname='$experimentDescription'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
$list[$row['description']] = array("id" => $row['id'], "type" => $row['type']);
}
return $list;
}
public function getDescriptionFromId($id) {
$query = "select * from $this->tableDescriptions where id='$id'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
if (mysql_num_fields($result) > 0) {
$row = mysql_fetch_array($result);
return array($row['type'], $row['description'], $row['experimentname']);
} else {
return false;
}
}
public function getDisplayName($experimentName) {
$query = "select displayName from $this->tableSpecs where experimentName='$experimentName'";
$result = mysql_query($query);
echo mysql_error();
$row = mysql_fetch_array($result);
if ($row) {
return $row['displayName'];
} else {
return false;
}
}
public function simpleQuery($query) {
$result = mysql_query($query);
echo mysql_error();
if ($result) {
$row = mysql_fetch_array($result);
if ($row) {
return $row[0];
} else {
return FALSE;
}
} else {
return FALSE;
}
}
public function rebin($tableSource, $tableTarget, $numSeconds, $sum = false) {
$this->createDataTable($tableTarget);
echo "Updating $tableSource to set rebinned from 0 to 2...";
$query = "update $tableSource set rebinned=2 where rebinned =0;";
mysql_query($query);
echo mysql_error();
echo "Done.\n";
$numRows = mysql_affected_rows();
echo "Found $numRows records in $tableSource that need rebinning...\n";
$query = "select id,from_unixtime(floor(unix_timestamp(min(time))/$numSeconds)*$numSeconds) as mintime from $tableSource where rebinned=2 group by id;";
$result = mysql_query($query);
echo mysql_error();
if ($result) {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$mintime = $row['mintime'];
echo $id . "...";
$query = "INSERT INTO $tableTarget (id,time,measurement,rebinned)
SELECT id,from_unixtime(floor(unix_timestamp(time)/$numSeconds)*$numSeconds)," . ($sum ? "sum" : "avg") . "(measurement) as measurement,0
FROM $tableSource WHERE id=$id && time>='$mintime'
GROUP BY id,floor(unix_timestamp(time)/$numSeconds)
ON DUPLICATE KEY UPDATE measurement=values(measurement), rebinned=0;";
mysql_query($query);
//echo $query;
echo mysql_error();
echo "Done.\n";
}
echo "Updating $tableSource to set rebinned from 2 to 1...";
$query = "update $tableSource set rebinned=1 where rebinned =2;";
mysql_query($query);
echo mysql_error();
echo "Done.\n";
}
}
public function getDCPower($experimentName, $startDate, $endDate) {
$out = array();
$query = $this->buildDCPowerQuery($experimentName, $this->tableMinbins);
if ($query) {
if ($startDate != "") {
$query = $query . " && m0.time>='$startDate' ";
}
if ($endDate != "") {
$query = $query . " && m0.time<='$endDate' ";
}
echo $query;
$result = mysql_query($query);
echo mysql_error();
while ($row = mysql_fetch_array($result)) {
// echo $row['time'].", ".$row['power']."\n";
$out[] = array($row['time'], $row['power'] + 0);
}
return $out;
} else {
return FALSE;
}
}
}
?>
Is there a way to make $database a string array which I can loop over for multiple database names?
No, it does not work that way. The script you have defines a class. You have to look in the file that uses that class, where there will be something like
$interface = new DatabaseInterface("database1");
There you'll be able to do things such as
$interface = array();
$interface[0] = new DatabaseInterface("database1");
$interface[1] = new DatabaseInterface("database2");
and use two instances of the interface against the two databases.
I'm writing a class and handful of functions to connect to the database and retrieve the information from the tables. I went through previous posts having similar titles, but most of them have written using mysql functions and I am using mysqli functions.
I want somebody who can go through this simple script and let me know where I am making my mistake.
This is my class.connect.php:
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
This is my index.php:
<?php
require_once ("class.connect.php");
$connection = new mySQL();
$connection->connect('localhost', 'myDB', 'joker', 'names_list');
$myquery = "SELECT * FROM list";
$query = $connection->query($myquery);
while($array = $connection->fetch($query))
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
I am getting the error saying that Error querying the Database.
Few problems :-
you don't die without provide a proper mysql error (and is good practice to exit gracefully)
fetch method is only FETCH the first row
mysqli have OO method, why you still using procedural function?
The problem is either this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
or this:
while($array = $connection->fetch($query))
Because you are using the result from the query to query again. Basically, you are doing:
$r = mysqli_query($this->dbc, $sql);
$array = mysqli_fetch_array(mysqli_query($this->dbc, $r));
And you are getting an error, because $r is not a query string. When it's converted to a string, it's a "1" (from your other comment).
Try changing the function to (changed name of variable so you can see the difference):
public function fetch($result)
{
return mysqli_fetch_array($result);
}
or just call the function directly.
If you don't do your own db abstraction for learning php and mysql, you can use Medoo (http://medoo.in/).
It's a free and tiny db framework, that could save a huge work and time.
Obviously an error occurs on SELECT * FROM list you can use mysqli_error to find the error:
return mysqli_query($this->dbc, $sql) or die('Error:'.mysqli_error($this->dbc));
This will display the exact error message and will help you solve your problem.
Try to check this
https://pramodjn2.wordpress.com/
$database = new db();
$query = $database->select(‘user’);
$st = $database->result($query);
print_r($st);
class db {
public $server = ‘localhost';
public $user = ‘root';
public $passwd = ‘*****';
public $db_name = ‘DATABASE NAME';
public $dbCon;
public function __construct(){
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db_name);
}
public function __destruct(){
mysqli_close($this->dbCon);
}
/* insert function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
*/
public function insert($table,$values)
{
$sql = “INSERT INTO $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}else{
return false;
}
$this->dbCon->query($sql) or die(mysqli_error());
return mysqli_insert_id($this->dbCon);
}
/* update function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
$condition = array(‘id’ =>5,’first_name’ => ‘pramod!’);
*/
public function update($table,$values,$condition)
{
$sql=”update $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}
$k=0;
if(!empty($condition)){
foreach($condition as $key=>$val){
if($k==0){
$sql .= ” WHERE $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$result = $this->dbCon->query($sql) or die(mysqli_error());
return $result;
}
/* delete function table name, array value
$where = array(‘id’ =>5,’first_name’ => ‘pramod’);
*/
public function delete($table,$where)
{
$sql = “DELETE FROM $table “;
$k=0;
if(!empty($where)){
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$del = $result = $this->dbCon->query($sql) or die(mysqli_error());
if($del){
return true;
}else{
return false;
}
}
/* select function
$rows = array(‘id’,’first_name’,’last_name’);
$where = array(‘id’ =>5,’first_name’ => ‘pramod!’);
$order = array(‘id’ => ‘DESC’);
$limit = array(20,10);
*/
public function select($table, $rows = ‘*’, $where = null, $order = null, $limit = null)
{
if($rows != ‘*’){
$rows = implode(“,”,$rows);
}
$sql = ‘SELECT ‘.$rows.’ FROM ‘.$table;
if($where != null){
$k=0;
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}
if($order != null){
foreach($order as $key=>$val){
$sql .= ” ORDER BY $key “.htmlentities($val, ENT_QUOTES).””;
}
}
if($limit != null){
$limit = implode(“,”,$limit);
$sql .= ” LIMIT $limit”;
}
$result = $this->dbCon->query($sql);
return $result;
}
public function query($sql){
$result = $this->dbCon->query($sql);
return $result;
}
public function result($result){
$row = $result->fetch_array();
$result->close();
return $row;
}
public function row($result){
$row = $result->fetch_row();
$result->close();
return $row;
}
public function numrow($result){
$row = $result->num_rows;
$result->close();
return $row;
}
}
The mysqli_fetch_array function in your fetch method requires two parameters which are the SQL result and the kind of array you intend to return. In my case i use MYSQLI_ASSOC.
That is it should appear like this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql), MYSQLI_ASSOC);
return $array;
}
**classmysql.inc.php**
<?php
class dbclass {
var $CONN;
function dbclass() { //constructor
$conn = mysql_connect(SERVER_NAME,USER_NAME,PASSWORD);
//$conn = mysql_connect(localhost,root,"","");
if(!$conn)
{ $this->error("Connection attempt failed"); }
if(!mysql_select_db(DB_NAME,$conn))
{ $this->error("Database Selection failed"); }
$this->CONN = $conn;
return true;
}
//_____________close connection____________//
function close(){
$conn = $this->CONN ;
$close = mysql_close($conn);
if(!$close){
$this->error("Close Connection Failed"); }
return true;
}
function error($text) {
$no = mysql_errno();
$msg = mysql_error();
echo "<hr><font face=verdana size=2>";
echo "<b>Custom Message :</b> $text<br><br>";
echo "<b>Error Number :</b> $no<br><br>";
echo "<b>Error Message :</b> $msg<br><br>";
echo "<hr></font>";
exit;
}
//_____________select records___________________//
function select ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^select",$sql)){
echo "Wrong Query<hr>$sql<p>";
return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if((!$results) or empty($results)) { return false; }
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results)) {
$data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
//________insert record__________________//
function insert ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^insert",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if(!$results){
$this->error("Insert Operation Failed..<hr>$sql<hr>");
return false; }
$id = mysql_insert_id();
return $id;
}
//___________edit and modify record___________________//
function edit($sql="") {
if(empty($sql)) { return false; }
if(!eregi("^update",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
$rows = 0;
$rows = #mysql_affected_rows();
return $rows;
}
//____________generalize for all queries___________//
function sql_query($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
if(!eregi("^select",$sql)){return true; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
function extraqueries($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
}
?>
**config.inc.php**
<?php
ini_set("memory_limit","70000M");
ini_set('max_execution_time', 900);
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
############################################
# Database Server
############################################
if($_SERVER['HTTP_HOST']=="localhost")
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
else
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
#############################################
# File paths
#############################################
// For the Database file path
include("system/classmysql.inc.php");
//For the inc folders
define("INC","inc/");
//For the Function File of the pages folders
define("FUNC","func/");
//For the path of the system folder
define("SYSTEM","system/");
$table_prefix = 'dep_';
################################################################
# Database Class
################################################################
$obj_db = new dbclass();
?>
**Function Page**
<?php
// IF admin is not logged in
if(!isset($_SESSION['session_id']))
{
header("location:index.php");
}
$backpage = 'page.php?type=staff&';
if(isset($_REQUEST['endbtn']) && trim($_REQUEST['endbtn']) == "Back")
{
header("location:".$backpage);
die();
}
// INSERT into database.
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")
{
$pass = addslashes(trim($_REQUEST['password']));
$password = encrypt($pass, "deppro");
$username = addslashes(trim($_REQUEST['username']));
$sql = "select * from ".$table_prefix."users where `UserName` ='".$username."'";
$result = $obj_db->select($sql);
if(count($result) == 0)
{
$insert="INSERT INTO ".$table_prefix."users (`UserName`)VALUES ('".$username."')";
$sql=$obj_db->insert($insert);
$newuserid = mysql_insert_id($obj_db->CONN);
}
header("location:".$backpage."msg=send&alert=2");
die();
}
// DELETE record from database
if(isset($_REQUEST['action']) && trim($_REQUEST['action'])==3)
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
$sql_del = "Delete from ".$table_prefix."users where StaffID ='$id'";
$del = $obj_db->sql_query($sql_del);
header("location:".$backpage."msg=delete&alert=2");
die();
}
}
// UPDATE the record
$action=1;
if((isset($_REQUEST['action']) && trim($_REQUEST['action'])==2) && (!(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")))
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
//$id = $_SESSION['depadmin_id'];
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$title = stripslashes($row['StaffTitle']);
$action=2;
}
}
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Update")
{
$title = addslashes(trim($_REQUEST['title']));
$sql_upd ="UPDATE ".$table_prefix."users SET `StaffTitle` = '$title' WHERE StaffID ='$id'";
$result = $obj_db->sql_query($sql_upd);
$action=1;
header("location:".$backpage."msg=edited&alert=2");
die();
}
}
}
if(isset($_REQUEST['vid']) && trim($_REQUEST['vid']!=""))
{
$id = site_Decryption($_REQUEST['vid']);
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$username = stripslashes($row['UserName']);
}
}
}
?>
<td class="center"><span class="editbutton"> </span> <span class="deletebutton"> </span> <a class="lightbox" title="View" href="cpropertyview.php?script=view&vid=<?php echo site_Encryption($sql[$j]['PropertyID']); ?>&lightbox[width]=55p&lightbox[height]=60p"><span class="viewbutton"> </span></a></td>
Receiving Error message when performing Update Statement, but database is being updated.
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
Issue with function update():
function update($pUInput) {
$sql = mysql_query("UPDATE tblStudents
SET first_name = '$pUInput[1]', last_name = '$pUInput[2]',
major = '$pUInput[3]',
year = '$pUInput[4]'
WHERE id = '$pUInput[0]'");
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record update";
}
Entire PHP Code:
//Call function mainline
mainline();
// Declare the function mainline
function mainline() {
$uInput = getUserInput();
$connectDb = openConnect(); // Open Database Connection
selectDb($connectDb); // Select Database
doAction($uInput);
//display();
//closeConnect();
}
//Declare function getUserInput ------------------------------------------------------------------------------------
function getUserInput() {
echo "In the function getUserInput()" . "<br/>";
// Variables of User Input
$idnum = $_POST["idnum"]; // id (NOTE: auto increments in database)
$fname = $_POST["fname"]; // first name
$lname = $_POST["lname"]; // last name
$major = $_POST["major"]; // major
$year = $_POST["year"]; // year
$action = $_POST["action"]; // action (select, insert, update, delete)
$userInput = array($idnum, $fname, $lname, $major, $year, $action);
return $userInput;
}
// function doAction ----------------------------------------------------------------------------------------------
function doAction($pUserInput) {
echo "In function doAction()" . "<br/>";
if ($pUserInput[5] == "select") {
//IDorLastName();
selectById();
} elseif ($pUserInput[5] == "insert") {
//checkStudentFields();
insert($pUserInput);
//echo "I need to insert!";
} elseif ($pUserInput[5] == "update") {
//IDorLastName();
update($pUserInput);
//echo "I need to insert!";
} elseif ($pUserInput[5] == "delete") {
//IDorLastName();
deleteById($pUserInput);
//echo "I need to insert!";
}
}
/*
function IDorLastName() {
if (!empty($pUserInput[0]) || !empty($pUserInput[2])) {
checkId();
} else {
echo "Please enter ID field or Last Name field";
}
}
}
*/
// function checkId -----------------------------------------------------------------------------------------------
/*
function checkId() {
if (!empty($pUserInput[0])) {
selectById();
} else {
selectByLastName();
}
}*/
/*
function checkStudentFields() {
// check if first name, last name, major and year exists
}*/
// Create a database connection ------------------------------------------------------------------------------------
function openConnect() {
$connection = mysql_connect("localhost", "root_user", "password");
echo "Opened Connection!" . "<br/>";
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
return $connection;
}
// Select a database to -------------------------------------------------------------------------------------------
function selectDb($pConnectDb) {
$dbSelect = mysql_select_db("School", $pConnectDb);
if(!$dbSelect) {
die("Database selection failed: " . mysql_error());
} else {
echo "You are in the School database! <br/>";
}
}
// Close database connection ------------------------------------------------------------------------------------
function closeConnect() {
mysql_close($connection);
}
// function selectById ---------------------------------------------------------------------------------------------
function selectById($pUInput) {
$sql = mysql_query("SELECT * FROM tblStudents
WHERE id='$pUInput[0]'");
if (!$row = mysql_fetch_assoc($sql))
{
die('Error: ' . mysql_error());
}
echo "selected" . "<br/>";
//echo $pUInput[0];
}
// function selectByLastName ---------------------------------------------------------------------------------------------
function selectByLastName($pUInput) {
$sql = mysql_query("SELECT * FROM tblStudents
WHERE last_name='$pUInput[2]'");
if (!$row = mysql_fetch_array($sql))
{
die('Error: ' . mysql_error());
}
echo "selected" . "<br/>";
echo $pUInput[2];
}
// function insert -------------------------------------------------------------------------------------------------
function insert($pUInput) {
$sql="INSERT INTO tblStudents (first_name, last_name, major, year)
VALUES
('$pUInput[1]','$pUInput[2]','$pUInput[3]', '$pUInput[4]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
// function update -------------------------------------------------------------------------------------------------
function update($pUInput) {
// call select();
$sql = mysql_query("UPDATE tblStudents
SET first_name = '$pUInput[1]', last_name = '$pUInput[2]',
major = '$pUInput[3]',
year = '$pUInput[4]'
WHERE id = '$pUInput[0]'");
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record update";
}
// function delete -------------------------------------------------------------------------------------------------
function deleteById($pUInput) {
// call select();
$sql="DELETE FROM tblStudents WHERE id='$pUInput[0]'";
$result=mysql_query($sql);
if($result){
echo "Deleted Successfully";
}else {
echo "Error";
}
}
/*
function display() {
}
*/
?>
SQL Syntax:
CREATE TABLE `tblStudents` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(30) NOT NULL,
`last_name` varchar(50) NOT NULL,
`major` varchar(40) NOT NULL,
`year` date NOT NULL,
PRIMARY KEY (`id`)
)
Try this:
$sql = "UPDATE tblStudents
SET first_name = '{$pUInput[1]}',
last_name = '{$pUInput[2]}',
major = '{$pUInput[3]}',
year = '{$pUInput[4]}'
WHERE id = '{$pUInput[0]}'";
if(!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record update";
And change this:
// Variables of User Input
$idnum = $_POST["idnum"];
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$major = $_POST["major"];
$year = $_POST["year"];
$action = $_POST["action"];
To:
// Variables of User Input
$idnum = mysql_real_escape_string($_POST["idnum"]);
$fname = mysql_real_escape_string($_POST["fname"]);
$lname = mysql_real_escape_string($_POST["lname"]);
$major = mysql_real_escape_string($_POST["major"]);
$year = mysql_real_escape_string($_POST["year"]);
$action = mysql_real_escape_string($_POST["action"]);
You might want to read up on sql injection.
Your id-column is of a numeric value and you're comparing it to a string-value. Computer says no.