PHP get single value from MySQL with variable [duplicate] - php

This question already has answers here:
Call to a member function prepare() on a non-object PHP Help [duplicate]
(8 answers)
Closed 2 years ago.
I can't seem to get simple query working to find UserID from the table of Users by UserEmail
I have simple function to suppose to return UserID
functions.php
function get_userID($UEml)
{
// Check database connection
if( ($DB instanceof MySQLi) == false) {
return array(status => false, message => 'MySQL connection is invalid');
}
$qSQL = "SELECT UsID FROM Users WHERE UsEml=? LIMIT 1";
$qSQL = $DB->prepare($qSQL);
$UEml = $DB->real_escape_string($UEml);
$qSQL->bind_param("s", $UEml);
$qSQL->execute();
$result = $qSQL->get_result();
while ($row = $result->fetch_row()) {
return $row[0];
}
// return $row[0];
if($qSQL) {
return array(status => true);
}
else {
return array(status => false, message => 'Not Found');
}
}
and I call it from php script
check-User.php
<?php
require_once("db-config.php");
include 'functions.php';
...
$UsID = get_userID("joe#example.com");
echo 'UserID: <span style="color: blue">'. $UsID ."</span>";
...
?>
db-config.php
<?php
// Two options for connecting to the database:
define('HOST_DIRECT', 'example.com'); // Standard connection
define('HOST_LOCAL', '127.0.0.1'); // Secure connection, slower performance
define('DB_HOST', HOST_DIRECT); // Choose HOST_DIRECT or HOST_STUNNEL, depending on your application's requirements
define('DB_USER', 'dbUser'); // MySQL account username
define('DB_PASS', 'SecretPas'); // MySQL account password
define('DB_NAME', 'DBName'); // Name of database
// Connect to the database
$DB = new MySQLi(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($DB->connect_error) {
die("Connection failed: " . $DB->connect_error);
}
//echo "Connected successfully";
?>
I tried many variations, but no luck and also checked many similar posts here, but just can't get it working.
Thanks

You have a couple of errors here:
$DB is not available in the function
the echo statement is wrong
This is the code without these 2 errors:
function get_userID($DB, $UEml)
{
// Check database connection
if ( ($DB instanceof MySQLi) == false) {
return array(status => false, message => 'MySQL connection is invalid');
}
$qSQL = "SELECT UsID FROM Users WHERE UsEml=? LIMIT 1";
$qSQL = $DB->prepare($qSQL);
$qSQL->bind_param("s", $UEml);
$qSQL->execute();
$result = $qSQL->get_result();
while ($row = $result->fetch_row()) {
return $row[0];
}
// return $row[0];
// I do not know why you wrote this code. If you get an user this code will not be executed
if ($qSQL) {
return array(status => true);
} else {
return array(status => false, message => 'Not Found');
}
}
And your echo:
// ...
$UsID = get_userID($DB, "joe#example.com");
echo "UserID: <span style=\"color: blue\">{$UsID}</span>";

Related

I called the data and tried using fetch_assoc but nothing appeared [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I made this to display data but nothing appeared,
and it shows no errors in coding
is there anyone who can help me
<?php
require 'db_connect.php';
$sql_get = "SELECT * FROM daftarumkm ORDER BY id_daftar DESC";
$query = $con->query($sql_get);
$response_data = null;
while ($data = $query->fetch_assoc()) {
$response_data[] = $data;
}
if (is_null($response_data)) {
$status = true;
} else {
$status = true;
}
and this is db_connect.php
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "data_umkm"); // database name
define('DB_SERVER', "localhost"); // db server
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);
// Check connection
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Your code for getting data from the database is fine, but there are some other issues.
1) If you want to check whether you got the results from database in the variable $response_data you have made a mistake here
if (is_null($response_data)) {
$status = true;
} else {
$status = true;
}
You probably want to change it to
if (is_null($response_data)) {
$status = false;
} else {
$status = true;
}
and I should mention thet there is a better way to do this. Instead of 4 lines above, you can simply write $status = (is_null($response_data)) ? false : true;
2) Furthermore, instead of all of the lines
$response_data = null;
while ($data = $query->fetch_assoc()) {
$response_data[] = $data;
}
if (is_null($response_data)) {
$status = true;
} else {
$status = true;
}
you can write the following more efficient code:
$response_data = $query->fetch_all(MYSQLI_ASSOC);
$status = ($response_data) ? false : true;
3) At the end, if you want to see the results, simply use the var_dumb() function.
var_dumb($response_data);

Php started with reporting 'unexpected' errors [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I'm making php chat to my school project. Php code is divided to two files with code. First file is file, where is chat window and text input to enter message. This is the php code of first file:
<?php
$connection = mysql_connect('localhost', 'root', 'root');
if (!$connection) {
die('<b>Can\'t connect to database server. Error message: ' . mysql_error() . '</b>');
}
$database = mysql_select_db('vaclavik', $connection);
if (!$database) {
$command = 'CREATE DATABASE vaclavik';
if (mysql_query($command, $connection)) {
echo '<b>Database wasn\'t found. New one has been created. </b>';
mysql_close($connection);
$connection = new mysqli('localhost', 'root', 'root', 'vaclavik');
$command = 'CREATE TABLE chat(datum DATETIME, zprava TEXT)';
if (mysqli_query($connection, $command)) {
die('New table has been created!');
}
else {
die('Can\'t create new table!');
}
}
else {
die('Database wasn\'t found and new one can\'t be created!');
}
}
mysql_close($connection);
$connection = mysqli_connect('localhost', 'root', 'root', 'vaclavik');
$command = 'SELECT * FROM chat';
$result = mysqli_query($connection, $command);
if(empty($result)) {
$command = 'CREATE TABLE chat(datum DATETIME, zprava TEXT)';
if (mysqli_query($connection, $command)) {
die('New table has been created');
}
else {
die('New table can\'t be created');
}
}
if (mysqli_num_rows($result) > 0) {
while($row = $result->fetch_assoc()) {
echo '<b>' . $row["datum"] . ":</b> " . $row["zprava"] . "<br />";
}
}
else {
echo '<b>No message found. Write something! :)</b>';
}
mysqli_close($connection);
?>
This code works. Then I created form to input message. It redirects to another file with php code to insert message into database. Problem is, if I put code with no error detections, it does nothing. And when I put there some error protetions, php starts report Parse errors with unexpected chars in code. Commonly '{' and 'echo'.
This is code of second file:
<?php
$message = $_POST["chatinput"];
$connection = mysqli_connect('localhost', 'root', 'root', 'vaclavik');
$command = "INSERT INTO chat (datum, zprava) VALUES (\'" . date("Y-m-d, h:i:sa") . "\', \'" . $message . "\')";
mysqli_query($connection, $command);
mysqli_close($connection);
echo "<script>window.location = \"../chat.php\"</script>";
?>

Query Checking for Existence - PHP

I'm trying to to test to see if an email address exists in my database by running a query check.
I can connect to the database fine.
However no matter what, even if the email exists it returns "doesn't exist".
<?php
//----------------------------------------------------------------------------------//
//Setup
require_once('SB_Constants.php');
//----------------------------------------------------------------------------------//
//Connect to the database
//----------------------------------------------------------------------------------//
$connection = mysqli_connect(DATABASE_HOST, SAVE_USERNAME, SAVE_PASSWORD, DATABASE_NAME);
// check the connection was successful
if (mysqli_connect_errno($connection)) {
header('HTTP/1.0 500 Internal Server Error', true, 500);
die(FailedToAccessDatabase . ". Failed to connect to Database");
} else {
echo "Connection Success!";
}
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($query_identifier) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#blah.com'");
echo $result;
}
/* close connection */
mysqli_close($connection);
?>
Any ideas of the problem? :)
Various mistakes. Fix:
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($assessorEmail) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_fetch_assoc($assessorEmail);
echo $result['ace_id'];
}
Your problem is mysqli_num_rows($query_identifier) is accessing an undefined variable instead of $assessorEmail.
Additionally, you only need one query if you just want the ace_id:
$assessorEmail = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#ablah.com'");
If mysqli_num_rows($assessorEmail) returns a row, than the email exists and you already have the ace_id
while(mysqli_fetch_assoc($assessorEmail) = $row) {
echo $result['ace_id'];
}

How do I connect to an SQLite database with PHP? [duplicate]

This question already has answers here:
Error: file is encrypted or is not a database
(7 answers)
Closed 5 years ago.
I have an SQLite database and am trying to connect to it with PHP. This is what I'm using:
<?php
$dbconn = sqlite_open('combadd.sqlite');
if ($dbconn) {
$result = sqlite_query($dbconn, "SELECT * FROM combo_calcs WHERE options='easy'");
var_dump(sqlite_fetch_array($result, SQLITE_ASSOC));
} else {
print "Connection to database failed!\n";
}
?>
However, I get this error:
Warning: sqlite_open() [function.sqlite-open]: file is encrypted or is not a database in C:\xampp\htdocs\deepthi\combadd\combadd_db.php on line 4
Connection to database failed!
What's wrong and how can I fix it?
Try to use PDO instead of sqlite_open:
$dir = 'sqlite:/[YOUR-PATH]/combadd.sqlite';
$dbh = new PDO($dir) or die("cannot open the database");
$query = "SELECT * FROM combo_calcs WHERE options='easy'";
foreach ($dbh->query($query) as $row)
{
echo $row[0];
}
$dbh = null; //This is how you close a PDO connection
Connecting To Database
Following PHP code shows how to connect to an existing database. If database does not exist, then it will be created and finally a database object will be returned.
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('combadd.sqlite');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
?>
Now let's run above program to create our database test.db in the current directory. You can change your path as per your requirement. If database is successfully created then it will give following message:
Open database successfully
SELECT Operation
Following PHP program shows how we can fetch and display records
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('combadd.sqlite');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
SELECT * FROM combo_calcs WHERE options='easy';
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "ID = ". $row['ID'] . "\n";
}
echo "Operation done successfully\n";
$db->close();
?>
<?php
if ($db = sqlite_open('sampleDB', 0666, $sqliteerror) ) {
$result = sqlite_query($db, 'select bar from foo');
var_dump(sqlite_fetch_array($result) );
} else {
die($sqliteerror);
}
?>
Make sure sqlite support is enable, check phpinfo()
One another solution to your problem is:
Using sqlite3 module instead
class DB extends SQLite3
{
function __construct( $file )
{
$this->open( $file );
}
}
$db = new DB( 'sampleDB.sqlite' );

MySQL Query: Trying to get property of non-object

I'm getting following error message.
Notice: Trying to get property of non-object in
C:\xampp\htdocs\my\include\user_functions.php on line 34
Here is my Code
$conn = db_connection();
if($conn == false) {
user_error('Unable to connect to database');
return false;
}
$query = "UPDATE user SET passwd = '".$new_passwd."'
WHERE username = '".$username."' ";
$result=$conn->query($query);
if($result == false) {
user_error('Query Error'.$conn->error);
return false;
}
if($result->num_rows == 1) {
echo 'Password changed';
} else {
echo 'Failed ';
}
here is my db_connection
function db_connection() {
$db = new mysqli('localhost','root','','php_login');
if(!$db) {
echo 'Could not connect to database server';
} else {
return $db;
}
}
The UPDATE statement doesn't return a result set. What are you trying to get from fetch_array?
UPDATE
class mysqli{
public $aff_num_rows;
//some properties
//some properties
//some methods
//some methods
public function query($sql)
{
$resultset = mysql_query($sql); //after query instantiate the $aff_numrows
//property with function
$this->aff_num_rows = mysql_affected_rows(); //guess you are using sqlite
//so you might have different function
//and you can use this property
}
}
And in you code you have
if($conn->aff_num_rows == 1) {
echo 'password changed';
} else {
echo 'error changing pasword';
}

Categories