i am trying to query one single row from a table 'account'. I kind mess up with the MYSQLI so i need some advice. How can i do that?
$link = mysqli_connect("localhost","root","","database") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM account WHERE username='".$user."' AND password='".$passcode."' LIMIT 1";
$result = $link->query($query) or die("Error " . mysqli_error($link));
$numrow = $result->num_rows;
$res = $result->fetch_assoc();
After the query i want to copy the data to a session, i am doing like that:
session_start();
$tableau = array($res['cod_acc'],$res['username'],$res['password']);
$_SESSION['tableau'] = $tableau;
And after these, how can i print the data?
$tableau = $_SESSION['tableau'];
echo "$tableau['username']";
From your question:
how can i print the data?
First of all you need to add error_reporting() on in your code:
error_reporting(E_ALL);
You are saving values in an array for $_SESSION:
$tableau = array($res['cod_acc'],$res['username'],$res['password']);
$_SESSION['tableau'] = $tableau;
If you look your session array it's not an associative array.
So you can not get the result like:
$tableau = $_SESSION['tableau'];
echo $tableau['username'];
Solution:
You can get username from session array as:
echo $tableau[1]; // username on second index.
Solution 2:
If you want associative index than you need to use associative array as:
$tableau = array(
"cod_acc"=>$res['cod_acc'],
"username"=>$res['username']);
$_SESSION['tableau'] = $tableau;
Now you can use as you need. Note that I am removing password field from session I think its not need.
Side note:
I don't know why are mixing Procedural and Objected Oriented style together.
The problem was in some other line code, sorry for the post. But thanks guys.
Related
I'm trying to select a value from a database and display it to the user using SELECT. However I keep getting this error:
Notice: Array to string conversion in (pathname) on line 36.
I thought that the #mysql_fetch_assoc(); would fix this but I still get the notice. This is the part of the code where I'm getting the error:
{
$loggedin = 1;
$get = #mysql_query("SELECT money FROM players WHERE username =
'$_SESSION[username]'");
$money = #mysql_fetch_assoc($get);
echo '<p id= "status">'.$_SESSION['username'].'<br>
Money: '.$money.'.
</p>';
}
What am I doing wrong? I'm pretty new to PHP.
The problem is that $money is an array and you are treating it like a string or a variable which can be easily converted to string. You should say something like:
'.... Money:'.$money['money']
Even simpler:
$get = #mysql_query("SELECT money FROM players WHERE username = '" . $_SESSION['username'] . "'");
note the quotes around username in the $_SESSION reference.
One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.
To echo elements of array properly, you can use the function, implode(separator, array)
Example:
implode(' ', $var)
result:
first name[1], last name[1]
first name[2], last name[2]
More examples from W3C.
Store the Value of $_SESSION['username'] into a variable such as $username
$username=$_SESSION['username'];
$get = #mysql_query("SELECT money FROM players WHERE username =
'$username'");
it should work!
mysql_fetch_assoc returns an array so you can not echo an array, need to print_r() otherwise particular string $money['money'].
You cannot echo an array.
Must use print_r instead.
<?php
$result = $conn->query("Select * from tbl");
$row = $result->fetch_assoc();
print_r ($row);
?>
I need to output like this.
{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.6192875","lng":"77.0261699"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6236227","lng":"77.0317984"},{"name":"","lat":"28.6244627","lng":"77.0322383"},{"name":"","lat":"28.6245415","lng":"77.0331425"},{"name":"","lat":"28.6245418","lng":"77.0331053"},{"name":"","lat":"28.6246156","lng":"77.0322415"},{"name":"","lat":"28.6242647","lng":"77.0316073"}
PHP Script
$sql="SELECT name,lat,lng FROM `in_point_creation` WHERE 1";
$result=mysql_query($sql);
while ($row=mysql_fetch_assoc($result)) {
$json_array = json_encode($row);
print_r($json_array);
}
Current Output
{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.6192875","lng":"77.0261699"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6236227","lng":"77.0317984"}{"name":"","lat":"28.6244627","lng":"77.0322383"}{"name":"","lat":"28.6245415","lng":"77.0331425"}{"name":"","lat":"28.6245418","lng":"77.0331053"}{"name":"","lat":"28.6246156","lng":"77.0322415"}{"name":"","lat":"28.6242647","lng":"77.0316073"}
Thanks
You need to create the entire object you need before calling JSON encode:
$sql="SELECT name,lat,lng FROM `in_point_creation` WHERE 1";
$result=mysql_query($sql); //You need to switch to mysqli , mysql is no longer a valid choice
$json_array = [];
while ($row=mysql_fetch_assoc($result)) {
$json_array[] = $row;
}
$jsonString = json_encode($json_array);
print_r($jsonString);
There are multiple ways to solve your "problem".
But first, don't use mysql_* functions => deprecated in PHP 5.5
Use mysqli_* functions instead.
If you have just a few hundred rows, you maybe could build an array with all items, like Paul Crovella and apokryfos said.
But if there are a multiple thousands of rows, you should prefer to write them out as quick as possible and don't save them to your RAM. Because PHP has limited space in RAM.
Maybe you could try it without loop:
$conn = mysqli_connect('host','username','password','database')
$query = 'SELECT name,lat,lng FROM `in_point_creation` WHERE 1';
$result = $conn->query($query);
$data = mysqli_fetch_all($result,MYSQLI_ASSOC);
echo json_encode($data);
To get an array like this array("123","456","789"); I use the code:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
{
$result_array[] = "\"".$row['regid']."\"";
}
$regIDs = implode(',', $result_array);
$registrationIDs = array($regIDs); // array("123","456","789");
but I would expect PHP/mySQL has a simpler/faster solution for this?
I doubt that your code produces the result you want.
// assuming the this query produces 123,456,789
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
// $row contains: array("123")
while($row = mysql_fetch_array($Regids))
{
$result_array[] = "\"".$row['regid']."\"";
}
// $result_array now contains: array("\"123\"", "\"456\"", "\"798\"");
$regIDs = implode(',', $result_array);
// $regIDS now contains a single string: "\"123\",\"456\",\"798\"";
$registrationIDs = array($regIDs);
// registrationIDs now is an array containing a single string: array("\"123\",\"456\",\"798\"");
If you really need an array that looks like this: array("123","456","789"); it is much simpler.
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
$registrationIDs[] = $row['regid'];
and that's all.
If your mysql result contains the number as an integer instead of an string you can convert it like this:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
$registrationIDs[] = strval($row['regid']);
Also, keep in mind that the mysql_* functions are becoming deprecated. Don't start new code with it and make plans to port your existing code to mysqli_* or PDO.
You can use PDO implementation. At first sight, it may be more difficult to understand, but once you get used to it, it reveals to be really powerful and handy (IMHO! One year ago i switched to it and i love it)!
For your example, the PDO implementation would be like this:
/*CONNECT TO DB, FIRST. $dbh contains a handler to the current DB connection*/
$stmt = $dbh->prepare("SELECT regid FROM table WHERE active = '1'");
$stmt->execute();
$Regids = $stmt->fetchAll(PDO::FETCH_COLUMN,0);
There are many formatting options you can specify, like
PDO::FETCH_COLUMN
PDO::FETCH_ASSOC
and more...These options will allow you to get the array formatted as you prefer. As you can see i got the result in just 3 simple rows.
EDIT
Note: you are not escaping PHP variables before inserting them in your Query, and your code may suffer SQL INJECTION. Be careful!! Here is a simple guide to prevent it.
(In my code, just to be clear, i avoided the problem by just putting the table name instead of $table, just to show simply how to get the result you wanted.)
try this .. use Group concat in query ...
$Regids = mysql_fetch_array(mysql_query("SELECT GROUP_CONCAT(regid) as regids FROM $tabel WHERE active = '1'"));
echo $Regids[0]['regids']; // 123,456,789
for getting result "123","456","789" try this
$Regids = mysql_fetch_array(mysql_query("SELECT GROUP_CONCAT('\"',CONCAT(regid),'\"') as regids FROM $tabel WHERE active = '1'"));
echo $Regids[0]['regids']; // "123","456","789"
can any one know the, convert mysql query in to an php array:
this is mysql query :
SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC
I want to convert this query in to simple php array .
So, you need to get data out of MySQL. The best way, hands down, to fetch data from MySQL using PHP is PDO, a cross-database access interface.
So, first let's connect.
// Let's make sure that any errors cause an Exception.
// <http://www.php.net/manual/en/pdo.error-handling.php>
PDO::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// We need some credentials...
$user = 'username';
$pass = 'password';
$host = 'hostname';
$dbname = 'database';
// PDO wants a "data source name," made up of those credentials.
// <http://www.php.net/manual/en/ref.pdo-mysql.connection.php>
$dsn = "mysql:host={$host};dbname={$dbname}";
$pdo = new PDO($dsn, $user, $pass);
There, we've connected. Let's pretend that $sql has the SQL you provided in your question. Let's run the SQL:
$statement = $pdo->prepare($sql);
$statement->execute();
There, it's been executed. Let's talk about results. You steadfastly refuse to tell us how you want your data structured, so let's go through four ways that you could get your data.
Let's first assume that the query returns a single row. If you want a numerically indexed array, you would do this:
// <http://www.php.net/manual/en/pdostatement.fetch.php>
$array = $statement->fetch(PDO::FETCH_NUM);
unset($statement);
If you want an associative array with the column names as the keys, you would do this:
$array = $statement->fetch(PDO::FETCH_ASSOC);
unset($statement);
Now, what if the query returns more than one record? If we want each row in a numerically indexed array, with each row as an associative array, we would do this:
// <http://www.php.net/manual/en/pdostatement.fetchall.php>
$array = $statement->fetchAll(PDO::FETCH_ASSOC);
unset($statement);
What if we want each row as a numerically indexed array instead? Can you guess?
$array = $statement->fetchAll(PDO::FETCH_NUM);
unset($statement);
Tada. You now know how to query MySQL using the modern PDO interface and get your results as no less than four types of array. There's a tremendous number of other cool things that you can do in PDO with very minimal effort. Just follow the links to the manual pages, which I have quite intentionally not linked for you.
This over-the-top post has been brought to you by the letters T, F and W, and the number PHP_MAX_INT + 1.
i don't get you clearly, but
mysql_fetch_array and mysql_fetch_assoc
both returns only array
please refer:-
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/en/function.mysql-fetch-assoc.php
If you just need a simple array...
while ($row = mysql_fetch_array($query)) { //you can assume rest of the code, right?
$result[$row['url_id']] = array($row['sumtime']);
}
For a simple array
$sql = mysql_query("SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC");
while($row = mysql_fetch_array($sql)){
$array1 = $row['sumtime'];
$array2 = $row['title'];
$array3 = $row['url'];
}
Hope this is one you wanted
Dude the fastest way is probably the following
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row;
}
print_r($data);
I have a PHP server script that SELECTs some data from a MySQL database.
As soon as I have the result from mysql_query and mysql_fetch_assoc stored in my own local variables, I want to delete the row I just selected.
The problem with this approach is that it seems that PHP has done pass-by-reference to my local variables instead of pass-by-value, and my local variables become undefined after the delete command.
Is there anyway to get around this? Here is my code:
$query="SELECT id, peerID, name FROM names WHERE peer = $userID AND docID = '$docID' AND seqNo = $nid";
$result = mysql_query($query);
if (!$result)
self::logError("FAIL:1 getUsersNamesUpdate() query: ".$query."\n");
if (mysql_num_rows($result) == 0)
return array();
$row = mysql_fetch_assoc($result);
$result = array();
$result["id"] = $row["id"];
$result["peerID"] = $row["peerID"];
$result["name"] = $row["name"];
$query="DELETE FROM names WHERE id = $result[id];";
$result = mysql_query($query);
if (!$result)
self::logError("FAIL:2 getUsersNamesUpdate() query: ".$query."\n");
return $result;
You are overwriting your $result variable with your second statement:
$query="DELETE FROM names WHERE id = $result[id];";
$result = mysql_query($query); // result does not contain the array anymore
Change the name to something else. It has nothing to do with call-by-reference or such.
Actually, your first assignment of the values is unnecessary as $row is already an array:
$row = mysql_fetch_assoc($result);
$result = array();
$result["id"] = $row["id"];
$result["peerID"] = $row["peerID"];
$result["name"] = $row["name"];
You could just do:
$row = mysql_fetch_assoc($result);
// at the end
return $row;
Then you don't even have to change your variable name for the second statement. But consider to use meaningful variable names.
First of all, why not just use only one query to delete the row that interests you ?
Something like this should do the trick, I suppose :
delete
from names
where peer = $userID
AND docID = '$docID'
AND seqNo = $nid
Of course, don't forget to escape/convert the values that should be ;-)
This way, no need for a select query, followed by a delete one.
Second : to make your code more easier to read / understand / maintain, you should probably not re-use the same variable for several different purposes.
Here, your $result variable is used for more than one thing, and it makes things harder to understand :
resource returned by the first mysql_query
then, array containing data from the first row
then, resource returned by the second mysql_query
It's a bit confusing, and will, one day or another, lead to errors...
Actually, it already has ;-) : the third assignment is overriding the data you're getting with the second ones, and boom, you've lost the information that corresponds to the row you've just deleted ;-)