When I run this php file shows me the error SQLSTATE [HY000]: General error. Why?
function Gethotspots($db) {
$regId = $_GET['regId'];
$sql = $db->prepare("INSERT INTO notificaciones (regId) VALUES ('" . $regId . "')");
$sql->execute();
$i = 0;
$pois = $sql->fetchAll(PDO::FETCH_ASSOC);
if (empty($pois)) {
$response["productos"] = array();
}
else {
foreach ($pois as $poi) {
$poi["actions"] = array();
$response["productos"][$i] = $poi;
$i++;
}
}
return $response["productos"];
}
$dbhost = "localhost";
$dbdata = "anuncios";
$dbuser = "root";
$dbpass = "";
try {
$db = new PDO("mysql:host=$dbhost; dbname=$dbdata", $dbuser, $dbpass, array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$response = array();
$response["productos"] = Gethotspots($db);
if (empty($response["productos"])) {
$response["errorCode"] = 20;
$response["errorString"] = "Ningun producto encontrado.";
} // if
else {
$response["errorCode"] = 0;
$response["errorString"] = "Todo correcto";
}
$jsonresponse = json_encode($response);
header('Access-Control-Allow-Origin: *');
echo $jsonresponse;
$db = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
Thanks all!
Related
I tried to connect my MySQL database kuvarskir with my PHP code. Then inputted this into html:
<?php
include "mysql.php";
$recepti = execute_sql("SELECT * FROM recepti");
foreach($recepti as $recept)
{
?>
<article>
<h2><?=$recept["naziv"]?></h2>
<i><?=$recept["sastojci"]?></i>
<p><?=$recept["uputstvo"]?></p>
</article>
<?php
}
?>
but its not working.
i think there is error with mysql.php file, here's the code:
<?php
function init_sql()
{
global $conn;
$host = "localhost";
$db = "kuvarskir";
$username = "root";
$password = "root";
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$conn = new PDO("mysql:host=$host;dbname=$db", $username, $password, $pdo_options);
}
catch(PDOException $e)
{
die("Database connection failed!");
}
}
function execute_sql($sql, $params=[])
{
global $conn;
if ($conn == null)
init_sql();
try
{
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$data = array();
if ($stmt->columnCount() == 0) //INSERT / UPDATE
return $stmt->rowCount();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
$data[] = $row;
return $data;
}
catch(Exception $e)
{
die("somting glitched. error is: $e");
}
}
?>
maybe, there is problem with my localhost, which is localhost:8080/phpmyadmin
also here is picture of database
I have the codes following for a delete process;
if(isset($_POST['deleteSong'])) {
$id = $_POST['deleteSong'];
$delete = $connect->prepare('DELETE FROM lyrica_songs WHERE id = ?');
$delete->execute(array($id));
$error = TRUE;
}
These codes is not deleting row. I have 7 columns at lyrica_songs and 3 of them are integers. ID (auto increment), song_singer_id and song_hit and when i run my codes ID, song_singer_id, song_hit are not deleted. I tried making them text instead integers and ID and song_hit still can't be deleted.
EDIT:
My connection code
<?php
$db_host = 'mysql:host=localhost;dbname=lyrica;charset=utf8';
$db_username = 'root';
$db_password = '';
try {
$connect = new PDO($db_host,$db_username,$db_password);
$connect->exec('SET NAMES UTF-8; SET CHARACTER SET UTF-8');
} catch (PDOException $error) {
echo "Veritabanı bağlantısı kurulamadı: " . $error->getMessage();
}
PDO version of #ChukwuemekaInya code
$db_host = 'localhost';
$db_username = 'root';
$db_password = '';
try {
$query = "DELETE FROM `lyrica_songs` WHERE `id`=:id ";
$dB = new PDO("mysql:host=$db_host;dbname=lyrica", $db_username, $db_password);
$stmt = $dB->prepare($query);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
return $stmt->execute();
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
$db_host = 'localhost';
$db_username = 'root';
$db_password = '';
try {
$connect = new PDO("mysql:host=$db_host;dbname=lyrica",$db_username,$db_password);
} catch (PDOException $error) {
echo "Veritabanı bağlantısı kurulamadı: " . $error->getMessage();
}
$delete = $connect->prepare('DELETE FROM lyrica_songs WHERE id = :id');
$delete->bindParam(':id', $id);
$delete->execute();
$delete->close();
I have the following code
<?php
$host = "localhost";
$dbname = "hawkI";
$user = "root";
$password = "";
$userExist = false;
$userIP = null;
$userHasFinish = null;
$userLastPage = null;
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
function getIPforBDD(){
return $_SERVER['REMOTE_ADDR'];
}
function UpdateUserProfile()
{
$requete = "SELECT * FROM users WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
if($resultat->rowCount() == 0)
exit();
foreach($result as $ligne)
{
$userIP = $ligne['ip'];
$userhasFinish = $ligne['finish'];
$userLastPage = $ligne['lastPage'];
}
}
function CheckUserPosition()
{
UpdateUserProfile();
if(!$userExist)
AddUser();
return GetUserStatus();
}
function GetUserStatus()
{
$page;
if($userHasFinish)
$page = "end.php";
else
$page = $userLastPage;
return $page;
}
function AddUser()
{
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
function SavePageInBDD($page){
$requete = "UPDATE users SET lastPage = '.$page.' WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
}
?>
But, I have a problem when I use it
( ! ) Notice: Undefined variable: dbh in C:\wamp64\www\HawkI\bdd.php
on line 66
I do not understand correctly how PHP work it's the first time I use it, but I tried to make
global $dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
That doesn't work too.
Also, it seems that value that are put outside of functions are not global like it would be in js, how can I make something accessible from everywhere (like file that include that file)
Thanks
Better way would be to do something like this:
function getDB(){
$dbh = null;
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
return $dbh;
}
And than in your functions do this:
function AddUser()
{
$dbh = getDB();
if(!is_null($dbh)){
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
}
To use $dbh inside a function, you need to include global keyword inside the function scope.
You can find the global keyword explanation here http://php.net/manual/en/language.variables.scope.php#language.variables.scope.global
function AddUser()
{
global $dbh;
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
You may use like this
$host = "localhost";
$dbname = "hawkI";
$user = "root";
$password = "";
$userExist = false;
$userIP = null;
$userHasFinish = null;
$userLastPage = null;
$dbh = NULL;
function db () {
try {
if ($GLOBALS['dbh']===NULL){
$GLOBALS['dbh'] = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
}
return $GLOBALS['dbh'];
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
function SavePageInBDD($page){
$dbh = db();
$requete = "UPDATE users SET lastPage = '.$page.' WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
}
I am getting the below error. I have copy paste the code. I have very little knowledge of PHP please guide me.
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/test_bader/public_html/include/connect.php on line 66
<?php
$DBHOST = "localhost";
$DBUSER = "tese_test";
$DBPASS = "";
$DB = "test_bader";
$default_dbname="test_bader";
*/
$DBHOST = "localhost";$
$Port= "3306";
$DBUSER = "test_test";
$DBPASS = "test#.";
$DB = "test_bader";
$default_dbname="test_bader";
$con=mysql_connect($DBHOST,$DBUSER,$DBPASS) or die(mysql_error());
mysql_select_db($DB);
function db_connect()
{
global $DBHOST, $DBUSER, $DBPASS, $default_dbname, $DB , $MYSQL_ERRNO, $MYSQL_ERROR;
$link_id = mysql_connect("$DBHOST","$DBUSER","$DBPASS");
if (!$link_id)
{
$MYSQL_ERRNO = 0;
$MYSQL_ERROR = "Connection Fail to the host $DBHOST.";
}
else if(empty($DB ) && !mysql_select_db($default_dbname))
{
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else if(!empty($DB ) && !mysql_select_db($DB ))
{
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else return $link_id;
}
function sql_error()
{
global $MYSQL_ERRNO, $MYSQL_ERROR;
if(empty($MYSQL_ERROR))
{
$MYSQL_ERRNO = mysql_erron();
$MYSQL_ERROR = mysql_error();
}
return "$MYSQL_ERRNO : $MYSQL_ERROR";
}
function q($st)
{
$r=mysql_query($st);
return $r;
}
function f($st)
{
$r=mysql_fetch_array($st);
return $r;
}
?>
<?php
$DBHOST = "localhost";
$DBUSER = "tese_test";
$DBPASS = "";
$DB = "test_bader";
$default_dbname="test_bader";
*/
$DBHOST = "localhost";$
$Port= "3306";
$DBUSER = "test_test";
$DBPASS = "test#.";
$DB = "test_bader";
$default_dbname="test_bader";
$con=mysql_connect($DBHOST,$DBUSER,$DBPASS) or die(mysql_error());
mysql_select_db($DB);
function db_connect()
{
global $DBHOST, $DBUSER, $DBPASS, $default_dbname, $DB , $MYSQL_ERRNO, $MYSQL_ERROR;
$link_id = mysql_connect("$DBHOST","$DBUSER","$DBPASS");
if (!$link_id)
{
$MYSQL_ERRNO = 0;
$MYSQL_ERROR = "Connection Fail to the host $DBHOST.";
}
else if(empty($DB ) && !mysql_select_db($default_dbname))
{
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else if(!empty($DB ) && !mysql_select_db($DB ))
{
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else return $link_id;
}
function sql_error()
{
global $MYSQL_ERRNO, $MYSQL_ERROR;
if(empty($MYSQL_ERROR))
{
$MYSQL_ERRNO = mysql_erron();
$MYSQL_ERROR = mysql_error();
}
return "$MYSQL_ERRNO : $MYSQL_ERROR";
}
function q($st)
{
$r=mysql_query($st);
return $r;
}
function f($st)
{
$r=mysql_fetch_array($st);
return $r;
}
?>
I'm trying to retrieve data from my table using PDO, only I can't seem to output anything to my browser, I just get a plain white page.
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$lastIndex = 2;
$sql = "SELECT * FROM directory WHERE id > :lastIndex AND user_active != '' LIMIT 20"
$sth = $conn->prepare($sql);
$sth->execute(array(':lastIndex' => $lastIndex));
$c = 1;
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo 'ALL STYLING ETC RESULTS HERE';
$c++;
}
$conn = null; // Disconnect
}
EXAMPLE.
This is your dbc class
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getAllData($qty) {
//prepared query to prevent SQL injections
$query = "select * from TABLE where qty = ?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $qty, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
$getList = $db->getAllData(25);
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}