This is one of my functions in my function.php file. Right now I'm just trying to get it to output 1 or 0 depending if the username is in the MYSQL DB.
function retrieve_single($col, $table, $item, $con) {
require_once('include/global.php');
$sql = "SELECT * FROM users WHERE username = Username1";
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($conn->connect_error) {
trigger_error('Database connection failed: '.$conn->connect_error, E_USER_ERROR );
}
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
echo $rows_returned;
}
}
I keep changing stuff around trying to figure out what's wrong with it, all I know it is a sql error I keep getting. As of right now I have it written without the variables because of trying to figure out the problem.
The global.php:
$DBServer = 'localhost'; $DBUser = 'root'; $DBPass = ''; $DBName = 'social';
Can anyone help me out! I know the problem is simple, as this is my first time having this problem
The error you say that you're getting and you haven't shown us, is caused by this:
WHERE username = Username1 ";
^ ^ // missing quotes
It needs to have single quotes placed around Username1
I.e.:
WHERE username = 'Username1'";
If you're not already doing so, add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Your function is very confusing. How are you calling it in the rest of your code?
function retrieve_single($col, $table, $item, $con) {
require_once('include/global.php');
$sql = "SELECT * FROM users WHERE username = Username1";
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($conn->connect_error) {
trigger_error('Database connection failed: '.$conn->connect_error, E_USER_ERROR );
}
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
echo $rows_returned;
}
}
So your interface to retrieve_single() has the following $col, $table, $item and $con. But where are they used in the function? They seem 100% not used at all. So you are just calling it like retrieve_single() and hope it works? Seems odd.
Then within your function your query is this:
$sql = "SELECT * FROM users WHERE username = Username1";
Which makes little sense. It should at least have single quotes around it like this:
$sql = "SELECT * FROM users WHERE username = 'Username1'";
But it seems like it should be a variable like this:
$sql = "SELECT * FROM users WHERE username = '$Username1'";
But that said, where would $Username1 come from? Perhaps—looking at your interface variables—that should be $item like this:
$sql = "SELECT * FROM users WHERE username = '$item'";
Perhaps the whole function needs to be refactored to accommodate all the oddities I noticed like this:
function retrieve_single($col, $table, $item, $con) {
require_once('include/global.php');
$sql = "SELECT $col FROM $table WHERE username = '$item'";
if ($con->connect_error) {
trigger_error('Database connection failed: '.$con->connect_error, E_USER_ERROR );
}
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
echo $rows_returned;
}
}
Using this refactored function you would access it like this outside of the function:
$con = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
retrieve_single('*', 'users', 'Username1', $con);
Then again, no idea how you are actually using your function in your larger code so this is me just winging it based on what you have presented. As it stands, the function itself—as you have presented it—is just problematic.
Related
<?php
getdata();
function getdata(){
$server="";
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server;
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
?>
This bit makes no sense to me:
function getdata(){
$server=""; //<---------- set here
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server; //<---- sure you want to do this
//your basically setting $row[1] = '' on every iteration
//so your command below is "nslookup " because $server = ''
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
It seems to me this bit $row[1]= $server; is backwards.
But lets not forget the SQLInjection issues here:
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
Specifically this stuff:
function updatenslookup($url,$nsresult) {
// ....
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
// ....
}
The big issue with it is I can inject whatever I want into this table, then you take that data and shoot it right into
exec("nslookup ".$row[1], $result); //simplified $server = $row[1] + exec("nslookup ".$server)
So in theory I can (or may be able to) inject my own command line calls into exec, at least to some extent. I'm not sure all what someone could do with these issues, what the worst case would be, but I would avoid it in any case.
There is no way for me to know where the data for updatenslookup($url,$nsresult) comes from or if its clean, but it doesn't matter. One reason to prepare the sql is to have the security right where the issue is so you can clearly tell by looking at just the query if its safe or not. And you don't have to worry about missing some piece of data that could sneak in there.
You should use escapeshellarg at the very least, and clean up the SQL vulnerabilities by preparing your queries.
As far as this Call to a member function fetch_assoc() on array, I don't even see a call to fetch_assoc() in your code. Maybe I missed it but all I see is this $row = mysql_fetch_row($result); for reading data, which is procedural where you use the OOP in the other code . which is irritating .. but I get it, which is why I only use PDO now...
Etc..
I always feel bad when I shred up someones hard work, but I would be remiss not to mention such a big security hole.
Cheers.
The previous programmer had used a class called database that has the connection string and a bunch of functions. I now have to convert this to MySQLi and I am at a loss.
class database {
var $sql='';
var $result='';
function database( $host='localhost', $user, $pass, $db) {
// perform a number of fatality checks, then die gracefully
if (!function_exists( 'mysql_connect' )) {
//or die( 'FATAL ERROR: MySQL support not available. Please check your configuration.' );
exit();
}
bla..bla..bla - bunch of code goes here
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysql_query($sql);
return $result;
}
}
I tried
var $link=mysqli_connect('localhost', $user, $pass);
to use as
$result = mysqli_query($link,$sql);
but I can not use expression as a variable value and I don't know what else to do.
Thanks a bunch! :)
try to use this.
I think it solves your problem.
<?php
$link = mysqli_connect("localhost", $user, $pass, $databaseName);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
mysqli_set_charset($link, "utf8");
?>
just bring the $link in every query.
$link = mysqli_connect("localhost", $user, $pass, $db);
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysqli_query($link,$sql);
return $result;
}
New to php and am connecting form attributes to php to connect to a godaddy mysql. Every attempt ends in a blank screen with no error messages. Is there any syntax errors the jump out? My sublime text wont register php syntax, but thats another problem for another time. I may need to call up godaddy support? the password has been removed for privacy.
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysql_select_db('EOTDSurvey', $con)
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
$_POST['BI1']
$_POST['BI2']
$_POST['BI3']
$_POST['BI4']
$_POST['BI5']
$_POST['BI6']
$_POST['BI7']
$_POST['BI8']
$_POST['BI9']
$_POST['BI10']
$_POST['BI11']
$_POST['BI12']
$_POST['BI13']
$_POST['BI14']
$_POST['BI15']
$sql = "INSERT INTO Survey1(BI1)"
$sql = "INSERT INTO Survey1(BI2)"
$sql = "INSERT INTO Survey1(BI3)"
$sql = "INSERT INTO Survey1(BI4)"
$sql = "INSERT INTO Survey1(BI5)"
$sql = "INSERT INTO Survey1(BI6)"
$sql = "INSERT INTO Survey1(BI7)"
$sql = "INSERT INTO Survey1(BI8)"
$sql = "INSERT INTO Survey1(BI9)"
$sql = "INSERT INTO Survey1(BI10)"
$sql = "INSERT INTO Survey1(BI11)"
$sql = "INSERT INTO Survey1(BI12)"
$sql = "INSERT INTO Survey1(BI13)"
$sql = "INSERT INTO Survey1(BI14)"
$sql = "INSERT INTO Survey1(BI15)"
if ($conn->query<$sql) === TRUE) {
echo "IT FUCKING WORKS.";
}
else{
echo "didnt workkkkkk";
}
$conn->close();
?>
please connect database like this...
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
And Use mysqli_select_db instead of mysql_select_db
And insert semi-colon (;) after every line end according to php code standard.
There are a lot of issues with this code, as mentioned the mysqli_select_db issue. The $_POST['BIx'] will also cause errors because there is no semi-colon after each statement. You're missing a '(' on the line if ($conn->query<$sql) === TRUE) { not to mention that line will not work anyway because you're logically comparing a resource type (I think) to a string.
You're also never executing the insert statements. All around I seriously think you should practice PHP coding some more and read up on how to use mysqli properly: see here.
Regards
EDIT: You also have a closing PHP tag at the end of your script which is generally not a good idea as explained here
EDIT 2: Also using an IDE such as Netbeans is always a good idea as it can highlight syntax errors instead of asking SO to do it for you ;)
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysqli_select_db('EOTDSurvey', $con);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
############# Function For Insert ##############
function insert($tableName='',$data=array())
{
$query = "INSERT INTO `$tableName` SET";
$subQuery = '';
foreach ($data as $columnName => $colValue) {
$subQuery .= " `$columnName`='$colValue',";
}
$subQuery = rtrim($subQuery,', ');
$query .= $subQuery;
pr($query);
mysqli_query($con,$query) or die(mysqli_error());
return mysqli_insert_id();
}//end insert
#########################################
if(isset($_POST['submit'])){
unset($_POST['submit']);
//print_r($_POST);
$result=insert('Survey1',$_POST);
if($result){
echo '<script>window.alert("Success!");</script>';
echo "<script>window.location.href = 'yourpage.php'</script>";
}
}
$conn->close();
?>
I'm trying to connect to a database, check a column for whether a value exists or not, then execute a function based on whether or not that value exists.
Here's my code.
$con = mysql_connect('localhost','root','','users');
$sql = "SELECT * FROM allUsers WHERE username = '".mysql_real_escape_string($_POST["username"]) . "'";
$result = mysql_query($sql,$con) or die("Error occurred in [$sql]: " . mysql_error());
$count = mysql_num_rows($result);
if ($count != 0){
echo "Username is already taken";
echo "$count";
mysql_close($con);
}
else{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
The thrown error is:
Error occurred in [SELECT * FROM allUsers WHERE username = 'Admin']: No database selected.
I'm almost entirely sure that it comes from the $result line, but haven't a clue as to why.
I feel like this is a simple solution, and I'm just missing something minor.
I'm very new to MySQL (today is my first day, actually), so please keep solutions as simple as possible.
You forgot to call mysql_select_db after connecting:
$con = mysql_connect('localhost','root','');
mysql_select_db('users', $con);
Unlike MySQLi or PDO, mysql_* libraries does not take database as argument on the connection string, however if you were to migrate to either MySQLi or PDO.
MySQLi:
$con = new mysqli('localhost', 'root', '', 'users');
PDO:
$con = new PDO('mysql:host=localhost;dbname=users', 'root', '');
In MySQLi your code would look like this:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database = "users";
$con = mysqli_connect($host,$user,$pass,$database);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$stmt = $con->prepare("SELECT * FROM allUsers WHERE username = ? LIMIT 1");
$stmt->bind_param('s',$_POST["username"]);
if (!$stmt->execute())
die('Failed to excute with error ' . $con->error);
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if ($count > 0)
{
echo "Username is already taken.";
}
else
{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
I think your error is quite obvious, you need to specify the database you want.
mysql_select_db("databaseName", $con);
With that taken care of, please, please don't use mysql_ libraries the are vulnerable to SQL injection and will soon be removed.
The code below works fine except it throws a warning when connecting to a database that does not exist. This works fine in product where errors are off, but I would rather not have errors if I don't need to.
function cpanel_db_connect($dbname) {
// normalize
$dbname = convert_to_slug($dbname);
$dbname = CPANEL_USER . '_' . $dbname;
$dbuser = CPANEL_USER . '_' . CPANEL_DB_USER;
// connnect database
$mysqli = new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);
if ($mysqli->connect_error) {
return false;
}
return $mysqli;
}
It's not a good practice to suppress warnings/errors using the # sign in PHP. You could accidentally suppress an invalid username or password message and you would never know it.
A more appropriate way of checking if the database exists is creating a new instance of Mysql or Mysqli (without specifying the default database) and executing the following query (similar to Marc B's comment):
SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME='my_database_name'
Then you can check the value of the key exists to see if the database is there or not.
Here's a sample code:
// statement to execute
$sql = 'SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME="my_database_name"';
// execute the statement
$query = $mysqli->query($sql);
// extract the value
$row = $query->fetch_object();
$dbExists = (bool) $row->exists;
It is a bit longer but it's safer.
$mysqli = #new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);
The above works!
This works, just replace $dbname in this code:
if (empty (mysql_fetch_array(mysql_query("SHOW DATABASES LIKE '$dbname' ")))){
echo "DB does Not exist"; }else{ echo "DB exists!";}
Updating to MYSQLI:
$conn = new mysqli('localhost', 'root', '');
$dbname='test';
if (empty (mysqli_fetch_array(mysqli_query($conn,"SHOW DATABASES LIKE '$dbname'"))))
{
echo "DB not exist<br>";
}
else
{
echo "DB exist<br>";
}
Here's how to connect to DB server without selecting a DB, and only connecting if DB exists:
$mysqli = new mysqli($db_biz['server'], $db_biz['user'], $db_biz['password']);
$query = 'SHOW DATABASES LIKE "' . $db_biz['dbName'] . '"';
$resShowBizDB = $mysqli->query($query);
if ($resShowBizDB->num_rows == 1) { //Found database
$mysqli->select_db($db_biz['dbName']);
if ($mysqli->connect_errno) { //Check for errors
var_dump($mysqli);
echo "Failed to connect to biz database: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$mysqli->set_charset('utf8');
} else { //Didn't find DB
die('<h1>ERROR</h1><p>Found no database</p>');
}