Query running in PHPmyadmin but not through PHP - php

I am trying to run a query from PHP which is not running but I can run the query from within phpMyAdmin
here is the code
<?php
ob_start();
//Delete Item question to admin and delete product
include"../storescripts/connect_to_mysql.php";
$conn = mysql_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete the item with ID '.$_GET['deleteid'].' ?Yes|No';
exit();
}
if(isset($_GET['yesdelete'])){
// Delete the actual product and delete picture also
//delete from database
$id_to_delete = $_GET['yesdelete'];
$manager=preg_replace('#[^A-Za-z0-9]#i','',$_GET['yesdelete']);
//$sql=mysql_query("SELECT id FROM admin WHERE username = '$manager' AND password='$password' LIMIT 1 ");
$sql = mysql_query( $conn ,"DELETE FROM products WHERE id=`$id_to_delete` LIMIT 1 ") or (mysql_error());
//echo 'The data at number ' . $id_to_delete . ' Deleted Sucessfully';
//mysqli_query("DELETE * FROM products WHERE id=`$id_to_delete`LIMIT1");// or (mysql_error());
//Unlink file from server
$pictodelete=("../inventory_images/$id_to_delete");
//echo $pictodelete;
if(file_exists($pictodelete)){
unlink($pictodelete);
}
// header("location:inventory_list.php");
//exit();
}
?>
I am new to PHP so your help is sought, i am able to connect to to database at another instance the code of which is following
<?php
//checking the user
ob_start();
session_start();
if (!isset($_SESSION["manager"])){
header ("location:admin_login.php");
exit();
}
//be sure to check if this manager SESSION value is in the database
$managerID=preg_replace('#[^0-9]#i','',$_SESSION["id"]);
$manager=preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["manager"]);
$password=preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);
//runMYSQL query to assertain that this is manager
//Connect to mysql database
include"../storescripts/connect_to_mysql.php";
$sql=mysql_query("SELECT*FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password'LIMIT 1");
// make sure person exists in database
$existCount=mysql_num_rows($sql);
if ($existCount== 0)
{
echo "your data do not match our records";
exit();
}
?>
The code in connect_to_my_sql.php is as follows
<?php
/*
1: "die()" will exit the script and show an error statement if something goes wrong with the "connect" or "select" functions.
2: A "mysql_connect()" error usually means your username/password are wrong
3: A "mysql_select_db()" error usually means that the database does not exist
*/
// Place db host name Sometimes "localhost" but
// sometimes looks like this:>> ???mysql??.someserver.net
$db_host = "localhost";
//Place the username for the MySQL database here
$db_username = "storeuser";
//Place the password for the MySQL database here
$db_pass = "rajjar";
//Place the name for the MySQL database here
$db_name="mystore";
// Run the actual connection here
$conn = mysql_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");
//mysql_select_db("$db_name") or die ("no database");
?>

Related

Executing SELECT query return false

I have a PHP site that I uploaded in 000webhost. It needs a database to store data. But when I try to sign in it didn't sign in. When I check the connection it turns out the connection was fine. Still not able to access the database. So I wrote a small script to check database access and it failed. I have a table named songs which contains some songs.
Here is the script :
<?php
ob_start();
session_start();
$host = 'localhost';
$user = 'xxxxxxx';
$pass = 'xxxxxxx';
$db = 'xxxxxxx';
$timezone = date_default_timezone_set("Asia/Kolkata");
$con = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
if($con)
{
echo "Connection success";
$query = mysqli_query($con, "SELECT * FROM songs");
if($query){
$tb = mysqli_fetch_array($query);
print_r($tb);
}
else {
echo " failed db access";
}
}
else {
echo " connection failed";
}
?>
The details have been kept hidden for security reasons.
The above script gives the following output:
Connection success failed db access
It doesn't work, because you're using PDO for connection and mysqli to query. Change your connection to mysqli
$con = new mysqli($servername, $username, $password, $dbname);
or change your query to PDO
$query = $con->query("SELECT * FROM songs");
The output you are showing is misleading, failed db access. As per below code, database was connected successfully and you were executing query, which didn't executed it seems and flow going to else block.
if($query){
// your code
}
else {
echo " failed db access";
}
You need to check,
If you are using same user credentials and has access to the table.
If same table exists
If you have provided correct database details where you have created tables.
==Updated==
As I mentioned earlier, user might not have sufficient privilege to access songs table. To GRANT access, you need to execute following SQL
GRANT ALL PRIVILEGES ON *.* TO '<username>'#'localhost; WITH GRANT OPTION;

MySQL Not Showing Data

I have a basic script below to show values from a database; it has worked for years now, but suddenly I'm getting empty results with no errors.
I'm thinking maybe the way to query data has changed? My script is below (note the db login details are correct, and connection is fine):
<?php
// Get Database Login
define("DB", dirname(dirname(__FILE__)) . "/");
require(DB . "../../ipSecure/db.ipSecure.php");
// End
// Connect To Database
$conn = mysql_connect($ipSecure_dbhost, $ipSecure_dbuser, $ipSecure_dbpass) or die ("Error Connecting to MYSQL");
mysql_select_db($ipSecure_dbname);
// End
// Find ipSecure Status
$ipSlicense = mysql_query("SELECT * FROM `license` WHERE `c_id` = 'inkgear-josh'");
$ipSlicense_result = mysql_fetch_assoc($ipSlicense);
// Show ipSecure Status
echo $ipSlicense_result["c_id"];
// End
?>
You can try this:
<?php
// Get Database Login
define("DB", dirname(dirname(__FILE__)) . "/");
require(DB . "../../ipSecure/db.ipSecure.php");
// End
// Connect To Database
/* ESTABLISH CONNECTION */
$conn=mysqli_connect($ipSecure_dbhost,$ipSecure_dbuser,$ipSecure_dbpass,$ipSecure_dbname);
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
// End
// Find ipSecure Status
$ipSlicense = mysqli_query($conn,"SELECT * FROM `license`");
while ($ipSlicense_result = mysqli_fetch_array($ipSlicense)){
// Show ipSecure Status
echo $ipSlicense_result['c_id'];
echo " - ".$ipSlicense_result['company_name']."; Status: ".$ipSlicense_result['status']."<br>";
// End
}
?>
I've convert your code to MySQLi at least, instead of deprecated MySQL.

Copying data from a MySQL table to another MySQL table not showing

I'm trying to make a registration form that validates the account by sending a validation code to the email. Once the user receive the code in his email he must click the link to validate his account(I simulated this using the localhost). BTW, I have 2 database for the registered members and for the temporary members(these are the members that are waiting for validation).
When the validation code is processed and matched, the data from the temporary table will be copied to the registered members table, after the copying is done the user data from temporary table will deleted.
when I checked my updated database(registered members table) the ID column had incremented but the username, password and email field has no data. what is the problem here?
here is the website I'm following for the tutorial but I did some little tweaks
http://phpeasystep.com/phptu/24.html
localhost/validated_email.php?passkey=639900974e5fc25626af1a6ce5da8b01
<html>
<body>
<?php
ob_start();
//define a function for temporary database (temporary_members)
function temporary_members_db(){
$host="localhost";
$db_username="root";
$db_password="";
$db="forum_members";
$db_table="temporary_members";
//=======================connect to database
mysql_connect("$host","$db_username","$db_password") or die("Could not connect to the database!");
mysql_select_db("$db") or die("database not found!");
}
function members_db() {
$host="localhost";
$db_username="root";
$db_password="";
$db="forum_members";
$db_table="members";
//=======================connect to database
mysql_connect("$host","$db_username","$db_password") or die("Could not connect to the database!");
mysql_select_db("$db") or die("database not found!");
}
//connect to the temporary_member table
temporary_members_db();
$code = $_GET['passkey'];
//execute mysql query to check the validation code
$check_code = "SELECT `validation_code` FROM `temporary_members`";
$execute_code = mysql_query($check_code);
$result_code = mysql_num_rows($execute_code);
if ($result_code==1) {
$rows=mysql_fetch_array($execute_code);
$username = $rows['username'];
$password = $rows['password'];
$email = $rows['email'];
$table_members = "members";
members_db();
$copy_values = "INSERT INTO $table_members(username, password, email) VALUES ('$username', '$password', '$email')";
$execute_copy = mysql_query($copy_values);
}
else {
echo "Wrong validation code";
}
if ($execute_copy) {
echo "Your account has been activated!";
//delete data from the temporary_members
$table_temporary_members = "temporary_members";
$delete_data = "DELETE FROM $table_temporary_members WHERE validation_code = '$code'";
$execute_delete = mysql_query($delete_data);
}
ob_end_flush();
?>
</body>
</html>

my code is not run on server. It shows no database selected

My connection file is conn.php, adminname and password are the table field name and form text box name. when this code run on server FTP it shows No database selected. But i include connection file and update database on FTP server. This code is run on local wamp server.
**my login coding is:**
// this is my login page.
<?php
session_start();
// start here session
include('conn.php');
// here include connection file
if(isset($_POST['login']))
{
$sql="select * from admin where adminname='".$_POST['adminname']."'and password='".$_POST['password']."'";
// this is my sql query which select adminname and password in table
$result=mysql_query($sql) or die(mysql_error());
if($result)
{
$row=mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
$_SESSION['admin']=$row['adminname'];
header("location:home.php");
}
else
{
header("location:index.php");
}
}
}
?>
add one line in conn file after getting connection from database
<?php
mysql_select_db ( string $database_name);
?>
Make sure about few things:
First check if you have created a database or not?
Make sure you entered the correct db_hostame, db_username, db_password, dbname
tricky way to make a database connection that works in your localhost and real server is:
$host = $_SERVER['HOST_NAME'];
if( $host == "localhost" ){
// localhost settings
}
else{
// Server Settings
}
it's just a simple trick.

Pass value from one php file to another php file

I create php file for my login.....
<?php
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$myusername=mysql_real_escape_string($_POST['uname']);
$mypassword=mysql_real_escape_string($_POST['passwd']);
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT uid FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if($row = mysql_fetch_assoc($result))
//echo mysql_result($result,0); // for correct login response
{
echo "User Found";
}
else {
echo "No Such User Found";
}
?>
It is just like this way...So here I select uid. I want get this uid & connect it to another php file. Really I want to get the details of the registered user by mapping so many tables. So I wrote the php file for that also. In the query inside that php file I want to equal the uid I get from above php file to the user_locator_tbl(the table in my database) uid. I did that. But I didn't think its correct. So pls help me.......
I gave here my other php file also....also I'm not fluent php...It is new to me...
<?php
require_once("dataget.php");
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
// Table name
$conn = mysqli_connect($host,$user,$pswd,$db);
//mysql_select_db($db, $conn);
//run the query to search for the username and password the match
//$query = "SELECT * FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$query = "select user_master.uid,device_locator_tbl.imei,device_locator_tbl.speed,device_locator_tbl.datetime,device_locator_tbl.number,device_master.icon
from device_locator_tbl,device_master,device_registration,user_master where user_master.uid=device_registration.uid
AND device_registration.imei=device_master.imei AND device_registration.imei=device_locator_tbl.imei AND user_master.uid='$query'";
//echo ($result);
$resultarray = mysqli_query($conn,$query) or die("Unable to verify user because : " );
//if($row = mysql_fetch_assoc($result))
if($row = mysqli_fetch_assoc($resultarray))
//echo mysql_result($result,0); // for correct login response
{
$rows[] = $row;
}
// close the database connection
mysqli_close($conn);
// echo the application data in json format
echo json_encode($rows);
?>
First off, you should use prepared statements, the mysql_ functions are deprecated in PHP and create a real issue for SQL injection, particularly in a login.
But using your example, refer to: PHP Login & MySql Query
The questioned code & answer there is perfectly pertinent to what you have thus far, and a simple, vastly more secure way to accomplish everything you need:
The original posters script you see is meant to store the users info into a $_SESSION[] array, from the database query like you have. Once the login attempt is validated the header(location:) call that you see in the original questions code will redirect the user to the location required.
Once the user is redirected, all the information from your user table query will be stored in the $_SESSION array and from then on accessible like $_SESSION[loggedinuser][userid], $_SESSION[loggedinuser][email] etc.
Remember to configure your PHP install appropriately for destroying sessions via a timeout, and also consider a logout function to destroy the user session.
So you should edit your first page like this ONLY IF you are NOT/CANNOT switching over to PDO - remember if you use sessions you should start session on page top:
<?php
session_start();
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$myusername=mysql_real_escape_string($_POST['uname']);
$mypassword=mysql_real_escape_string($_POST['passwd']);
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT uid FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if($row = mysql_fetch_assoc($result))
//echo mysql_result($result,0); // for correct login response
{
$_SESSION['uid'] = $row['uid'];
header("Location: nextpage.php");
//echo "User Found";
}
else {
echo "No Such User Found";
}
?>
And You can catch this value from next page like this:
<?php
session_start();
// this section validate your inner files no one can enter this file without login
if(empty($_SESSION['uid'])){
header("Location: index.php");
}
// now you can do whatever you like
echo $_SESSION['uid'];
require_once("dataget.php");
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
// Table name
$conn = mysqli_connect($host,$user,$pswd,$db);
//mysql_select_db($db, $conn);
//run the query to search for the username and password the match
//$query = "SELECT * FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$query = "select user_master.uid,device_locator_tbl.imei,device_locator_tbl.speed,device_locator_tbl.datetime,device_locator_tbl.number,device_master.icon
from device_locator_tbl,device_master,device_registration,user_master where user_master.uid=device_registration.uid
AND device_registration.imei=device_master.imei AND device_registration.imei=device_locator_tbl.imei AND user_master.uid='$query'";
//echo ($result);
$resultarray = mysqli_query($conn,$query) or die("Unable to verify user because : " );
//if($row = mysql_fetch_assoc($result))
if($row = mysqli_fetch_assoc($resultarray))
//echo mysql_result($result,0); // for correct login response
{
$rows[] = $row;
}
// close the database connection
mysqli_close($conn);
// echo the application data in json format
echo json_encode($rows);
?>

Categories