I was trying to add a new user to the database with the next user id of last user's ID but its not happening.
function addNewUser($addUserName, $addUserEmail, $addUserPassword, $addUserAuthLevel){
$dbHost = "localhost";
$dbUser = "admin";
$dbPassword = "d4shb5w";
$dbName = "masterDatabase";
$connection = mysqli_connect($dbHost,$dbUser,$dbPassword, $dbName);
//test if connection occurred
if(mysqli_connect_errno()){
die("Database connection failed: " . mysqli_connect_error() . "(" . mysqli_connect_errno() . ")");
};
//adding new userInformation into database
$queryLastUserId = "SELECT * FROM userlogindetails ORDER BY userId DESC ";
$LastUserId = mysqli_query($connection, $queryLastUserId);
if($id=mysqli_fetch_assoc($LastUserId)){
$userId=$id["userId"]+1;
}
$userName = mysqli_real_escape_string($connection,$addUserName);
$userEmailId = mysqli_real_escape_string($connection,$addUserEmail);
$userPassword = $addUserPassword;
$passwordHash = password_hash($userPassword, PASSWORD_DEFAULT);
$userAuthLevel= $addUserAuthLevel;
$queryNewUser = "INSERT INTO userlogindetails(userId, userName, userEmailId, userPassword, userLoginTime, userAuthLevel) VALUE ($userId,'$userName', '$userEmailId', '$passwordHash', Now(),'$userAuthLevel')";
$result = mysqli_query($connection, $queryNewUser);
if($result){
mysqli_close($connection);
return "Success "/*.$userId*/;
}else{
mysqli_close($connection);
return "Failed "/*.$userId*/;
}
}
But when I assign usedId statically then it works fine.
What is the problem in the code?
Use the MAX function in a PHP function to get the value. This is a better practice.
function getMaxID($db){
$result = mysqli_query($db, "SELECT MAX(userId) FROM userlogindetails;");
return mysqli_fetch_assoc($result)["MAX(userId)"];
}
Note: I agree with the comments thus far: You should set the primary key to be auto-incrementing. That is an even better practice. MySQL workbench is a great (free) place to start, if you're not yet familiar with data structures.
All this can be done with simply making the id auto_increment in the database. Edit your table.
You need to assign a default value to your $userId variable (e.g. $userId = 1; at the beginning of the function).
If you don't initialize it and in your table there is no users your code will crash.
Related
<?php
$q= $_REQUEST["q"];
$r = $_REQUEST["r"];
$s = $_SESSION['empid'];
$max = 0;
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'employeesurvey';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$sql1 = "SELECT QuestionID FROM question";
if(!mysqli_query($conn,$sql1)){
echo 'error2 php';
}
while($rw1 = mysqli_fetch_array($sql1)){
$Q = $rw1['QuestionID'] ;
if ($max<$Q){
$max = $Q;
}
}
$Q = $Q+1;
$sql = "INSERT INTO question VALUES (".$Q.",'".$r."',".$s.",CURRENT_DATE(),".$q.",0)";
if(!mysqli_query($conn,$sql)){
echo "Error";
}
?>
The db, table names are all correct. I'm using xmlHttpRequest.open() to pass the values to this page
the call statement is:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "gethint1.php?q=" + cid + "&r=" + question, true);
Im not getting any errors, nor the values are being inserted
Replace this line:
if(!mysqli_query($conn,$sql1)){
with these
$resultSet = mysqli_query($conn,$sql1);
if(!$resultSet){
And now replace this line:
while($rw1 = mysqli_fetch_array($sql1)){
With this one
while($rw1 = mysqli_fetch_array($resultSet)){
Reason is that you haven't executed query and stored the result set while at fetching record from result set, you are using direct query variable which is logically wrong.
why are you making a simple thing this complicated by obtaining Question id from table just use autoincrement field in your mysql table or use insert_id
and the problem is mysqli_fetch_array() function works on mysqli_query() function's output i.e. a object you are providing a string to a function which expects an object
I am using eclipse editor. I am programming within vtiger 5.4. in my file config.inc.php the variable $default_charset is setted as
$default_charset = 'UTF-8';
I'm trying to make a sql query in mysql using the next variable
$sql = "select cod_dpto from vtiger_ubi where dpto='" . $dpto . "'";
When I print the variable $dpto I get "SAÑA", but the execution of the query mysql
$adb->query ( $sql );
doesn't work. But when I modify my query as:
$sql = "select cod_dpto from vtiger_ubi where dpto='SAÑA'";
the instruction
$adb->query ( $sql );
returns the values that I need.
Could you help me please, how can I convert my variable $dpto such that the sql query works well.
EDIT
I trying to make the query with the below code, without vtiger, and I get 0 results for thw two cases with variable and writing 'SAÑA'
$servername = "localhost";
$username = "root";
$password = "peru2006";
$dbname = "consuladoperurio_com_br_2";
$port = "3306";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname, $port );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "select cod_dpto from vtiger_ubigeo where dpto='$dpto'";
echo $sql;
$result = $conn->query ( $sql );
if ($result->num_rows > 0) {
// output data of each row
while ( $row = $result->fetch_assoc () ) {
echo "id: " . $row ["cod_dpto"] "<br>";
}
} else {
echo "0 results";
}
$conn->close ();
Your Select statement looks like this:
$sql = "select cod_dpto from vtiger_ubi where dpto='".SAÑA."';
you'll probably want it to look like:
$sql = "select cod_dpto from vtiger_ubi where dpto='$dpto'";
Notice no concat operator, and the variable is only wrapped in single quotes.
I am using this same code `
php $postId = 41;
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname="my_db";
$host="localhost";
$user="guessthe";
$dbh=mysql_connect ($host,$user,"correctPassword?") or die ('I cannot connect to the database because: ' . mysql_error(). '');
mysql_select_db ("$dbname") or die('I cannot select the database because: ' . mysql_error());
$sql="SELECT * FROM games WHERE postId = $postId";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
There is a value in the gameLength row! I can't get this code to pull any of the rows! Any idea what i'm doing wrong?
You're using MySQL, which is depcirated - and will be phased out. You should use MySQLi or PDO instead. Also, your $postId is defined outside a PHP-tag? Might just be a copy/paste mistake? Anyway, you can try the code below, which is in MySQLi:
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname = "my_db";
$host = "localhost";
$user = "guessthe";
// Connecting to the database
$mysqli = new mysqli($host, $user, "correctPassword?", $dbname);
if ($mysqli->connect_errno) {
// If we are here, the connection failed
echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql ="SELECT * FROM games WHERE postId = $postId";
if ($result = $mysqli->query($sql)) {
// If the query was sucsessfull, we can get the rows
while ($row = $result->fetch_assoc()) {
$gameId = $row['id'];
$game100s = $row['game100s'];
$gamesPlayedAllTime = $row['gamesPlayed'];
$gamesPointsAllTime = $row['gameScore'];
$gameLength = $row['gameLength']; // get number of questions
$gameScore = $row['gameScore'];
$gameType = $row['gameType'];
$gametitle = $row['gameSubTitle'];
}
} else {
// If the query failed, do something here
}
echo $gameLength;
?>
I see some people commenting that you need to put the $postId variable inside quotes in the query, but when using double-quotes (") variables will be posted, so it's not really needed. Also note that things are case-sensitive, so if your results doesn't show, check for spelling-mistakes.
There are many errors in your code
Try this...
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength">
<?php
// MySQL connect configuration
$host = "localhost";
$dbname = "my_db";
$user = "username";
$password = "password";
$dbh = mysql_connect ($host,$user,$password) or die ('I cannot connect to the database because: ' . mysql_error() . '');
mysql_select_db($dbname, $dbh) or die('I cannot select the database because: ' . mysql_error());
$sql = "SELECT * FROM games WHERE postId='$postId'";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)){
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
}
?>
You need to fix this is your code and that should fix the error.
$sql="SELECT * FROM games WHERE postId ='".$postId."' ";
If you want all the records you can use a while loop. Here is some pseudo code.
while($row = mysql_fect_assoc($query)){
echo $row["THE THING YOU WANT"];
...
}
I'm sure the question is easy to answer, but I don't get it.
When I try to connect in a function it throws me an "Access denied for user''#'localhost'" error. It looks like the array isn't available in the array, because the error says I didn't enter a username and password.
The code is:
$config["mysql_host"] = "localhost";
$config["mysql_user"] = "myusername";
$config["mysql_pass"] = "mypass";
$config["db_name"] = "mydb_name";
$config["event_tname"] = "tablename";
function get_events(){
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die ("Error, please contact the provider!"/* . mysqli_error()*/); //execute
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
events(); //just an example: call the function
What do I have to change at the array?
Regards,
Franz
At first you should consider using mysqli object-orientated. There is no reason to use procedural style anymore.
Secondly global PHP variables are not available inside of functions, therefore you need to pass the array to the function as explained in the other answer.
See this article for more information on PHPs variable scope.
Imho the best solution would be to use a class for your application and store the config as private attributes. Methods of that class will then have access to the attributes.
just add global $config; inside your function as
function get_events(){
global $config;
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error());
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
get_events(); //ju
or pass the config param to function
function get_events($config){
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error());
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
get_events($config); //ju
I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:
Fatal error: Call to a member function fetch_row() on a non-object in...on line 23.
The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?
class mySQLHelper{
public function checkPass($user, $pass){
global $db;
$db = new mysqli();
$db->connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()){
echo 'Can not connect to database';
echo mysqli_connect_errno(). mysqli_connect_error();
exit;
return false;
}
$query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;
echo $query;
$results = $db->query($query);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
$results->close();
$url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
if(!$results){
// mysqli_close($db);
// header("Location:.$url.login.php&msg=1");
}
else{
// mysqli_close($db);
// header("Location:.$url.featured.php");
}
}
}
Your query is failing on this line:
$results = $db->query($query);
Because of this, $results is false - not a result object as you expect.
To fix the issue, you need to add quotes around your variables (or use prepared statements):
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:
$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();
You script is lacking error checking, and therefore the error in the query is not handled.
$query = "SELECT user, password FROM Users
WHERE user = '$user' AND password = '$pass' " ;
// ^ quotes needed
echo $query;
$results = $db->query($query);
// handle a error in the query
if(!$results)
die($db->error);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
If you user & password field text or varchar, then you need to use single quote around them
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
You have to check, if query runs properly:
if ($result = $mysqli->query($query))
{
}
Use: var_dump($results) to check what it contains
Why are you checking if($results) after trying to manipulate it?
This...
$results->close();
//...
if(!$results){
//...
}
Should be...
if(!$results){
//...
}
$results->close();