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.
Related
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"];
...
}
When i run the following code it will return 100 users record from a table but when i increase the value of LIMIT from 100 to a greater number like 5000 then it will not return anything.i have total 6000 records in table. So how can i access different number of records like 2000, 3000 or even all 6000 records? kindly Guide what's wrong!
<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());}
mysql_select_db("distributedsms",$db);
$result = mysql_query("select * from users LIMIT 100", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['user no'] = $row['sno'];
$row_array['mnc'] = $row['mnc'];
$row_array['mcc'] = $row['mcc'];
$row_array['lac'] = $row['lac'];
$row_array['cell id'] = $row['cell id'];
$row_array['lat'] = $row['lat'];
$row_array['lng'] = $row['lng'];
$row_array['address'] = $row['address'];//push the values in the array
array_push($json_response,$row_array);
$users = $json_response;}
$fp = fopen('users_data.json', 'w+');
fwrite($fp, json_encode($json_response));
fclose($fp);
echo json_encode($json_response);
?>
First, enable error reporting in your INI or Script:
<?php error_reporting(E_ALL);
ini_set('display_errors', 1);
This will help you if there is any error/warning in case of low memory allocation or similar.
To fetch all records, you shouldn't use LIMIT, remove LIMIT from your SQL.
i.e. select * from users
You should not use mysql_connect as it is deprecated. Use mysqli_connect instead. Also, I don't think you need to iterate so much, just choose what you want in your select statement.
UPDATE: another factor on why this might be happening can also be the returned information from the database, if you have apostrophes ' in your strings and you try to use json_encode, it will break, you would need to addslashes first.
Try the following, change your LIMIT as you wish, and let me know if you still have those errors:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT sno,mnc,mcc,lac,cell_id,lat,lng,address FROM users LIMIT 100";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$response = array();
while ($row = $result->fetch_assoc()) {
foreach($row as $k => $str){
$row[$k] = addslashes($str);
}
array_push($response, $row);
}
echo json_encode($response);
} else {
echo "0 results";
}
$conn->close();
?>
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 have a working SQL query that I'm trying to use in a small PHP script but getting Parse error, tried many variations. Hope you can help. End result would be to have a two field form with 'Date' and 'Channel No' then giving result count of number of 'channel' rows for a given date. Sorry fairly new PHP/SQL, thanks.
<?php
// Connect to MSSQL and select the database
$link = mssql_connect('localhost', 'root', '', 'jm_db');
mssql_select_db('jm_db');
// Select all our records from a table
$mysql_query = mssql_query ('SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%');
echo $sql;
?>
I have re-done the code but getting 'Warning: mysql_fetch_array() expects parameter 1 to be resource' and undefined variable.
<?php
// Create connection
$mysqli = new mysqli($localhost, $root, $jm_db);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = ("SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%'");
$results= array();
while ($result = mysql_fetch_array($sql)) {
$results[]= $result;
}
foreach($results as $result){
echo $result['calldate'] . " " . $result['channel'];
}
?>
You're missing a quote (Stack's syntax highlighting shows you), yet it should be replaced with an opening double quote and ending with the same. You can't use all single quotes.
I replaced the opening single quote with a double, along with a matching closing double quote.
$mysql_query = mssql_query ("SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%'");
As a sidenote, you're echoing the wrong variable.
However, that is not how you would echo out results, but with a loop.
Something like, and replacing Fieldname with the one you want to use:
while ($row = mssql_fetch_assoc($mysql_query)) {
print $row['Fieldname'] . "\n";
}
or use mssql_fetch_array()
You can also use:
$results= array();
while ($result = mssql_fetch_array($mysql_query)) {
$results[]= $result;
}
foreach($results as $result){
echo $result['calldate'] . " " . $result['channel'];
}
For more information on Microsoft SQL Server's function, consult:
http://php.net/manual/en/book.mssql.php
$mysql_query = mssql_query ('SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%');
while($row=mssql_fetch_array($mysql_query))
{
echo $row[0];
}
$mysqli = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysql_query = mysqli ("SELECT COUNT(*) FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");
while ($row = mysql_fetch_array($mysql_query, MYSQL_ASSOC)) {
echo ($row["channel"]);
}
this is a simple example with PDO
<?php
try {
$dns = 'mysql:host=localhost;dbname=jm_db';
$user = 'root';
$pass = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$cnx = new PDO( $dns, $user, $pass, $options );
$select = $cnx->query("SELECT COUNT(*) as count FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");
$select->setFetchMode(PDO::FETCH_OBJ);
while( $row = $select->fetch() )
{
echo '<h1>', $row->count , '</h1>';
}
} catch ( Exception $e ) {
echo "Connect failed : ", $e->getMessage();
die();
}
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.