I need to store the values of the column 'following' in an array. However, I can't figure out what's wrong with this code.
session_start();
$connect = mysqli_connect("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$result = mysql_query("SELECT * FROM Followers WHERE user='$user'");
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row['following'];
}
It's easier to use a jointure, which will be far more efficient :
Select * from message left join followers on followers.following=Messages.user where Follower.user=...
HTH
Regards
Your solution will encounter problems if you forget to escape caracters like " ' " or " " " or even " \ ".
If I was you, I'd merge into a subquery this way:
$sql = "SELECT * FROM Messages WHERE user IN
(SELECT * FROM Followers WHERE user='$user')"
$result = mysqli_query($connect, $sql );
cheers!
Replace the below
mysql_fetch_array($result) with mysqli_fetch_array($result)
Hope it works!
try this
session_start();
$connect = new mysqli("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$result = mysqli_query($connect,"SELECT * FROM Followers WHERE user='$user'");
$data = array();
while ($row = mysqli_fetch_array($result)) {
$data[] = $row['following'];
}
As was pointed out you ought to use a prepared statement to avoid nasty sql injection. As the only field that is being used is follower limit the columns returned ( makes it easier using below notation - notably bind_result )
session_start();
$data = array();
$db = new mysqli("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$sql='select `following` from `followers` where user=?';
$stmt=$db->prepare($sql);
if( $stmt ){
$stmt->bind_param('s',$user);
$res=$stmt->execute();
if( $res ){
$stmt->bind_result($follower);
while( $stmt->fetch() ){
$data[]=$follower;
}
$stmt->free_result();
$stmt->close();
}
}
$db->close();
You have 3 errors in code:
1.mysql_query() is deprecated and may give error so use mysqli_query() which expects 2 paramter connection and query.
2.Your query is not receiving user variable value since its a string.
3.Your row is not an associative array for which you can get following value so use mysqli_fetch_assoc() instead.
You can use the following code:
$connect = mysqli_connect("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$result = mysqli_query($connect,"SELECT * FROM followers WHERE user='".$user."'");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[]=$row['following'];
}
Related
I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>
How to Convert mysql all tables to json(How to Select Multiple tables, not one);
I am trying to select multiple table of my db:
then convert it from mysql to json format
Please guide me!
<body>
<?php
$connect = mysqli_connect("localhost", "root", "", "martlink_db");
$sql = "SELECT * FROM users";
$result = mysqli_query($connect, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo '<pre>';
print_r(json_encode($json_array));
echo '</pre>';
//echo json_encode($json_array);
?>
</body>
Check the following query
<?php
$connect = mysqli_connect("localhost", "root", "", "martlink_db");
$sql ="SELECT * FROM table1 t1,table2 t2 where condition"
$stmt = $conn->query($sql);
$jsonArr = array();
do
{
$rowset = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rowset)
{
$jsonArr[] = tojson($rowset, $i);
}
}while ($stmt->nextRowset());
?>
for a customer I have to make little adjustments to an application what is build on OOP PHP. I have no experience at all with OOP, and normally I only use PHP for small functions. I would like to select data from my database, to use it in a build function and variable. My code under will explain
public function readTwitter(){
$accounts = array();
$hastags = array('coldplay');
\ORM::for_table('feed_items')->where('portal_reference', 'tw')->delete_many();
foreach($accounts as $account) {
$feed = $this->twitter->getFeedByAccount($account);
foreach($feed as $post){
$this->twitter->savePost($post);
}
}
foreach($hastags as $hashtag) {
$feed = $this->twitter->getFeedByHashtag($hashtag);
foreach($feed->statuses as $post){
$this->twitter->savePost($post);
}
}
}
So in this version of the application the foreach loop will check if the var is filled in, what is now done with an array, and use it in the function readTwitter() What I like to have is a select query which selects one specific row out of my database to use it instead of an array, written in my application as OOP as follow (written in procedural php):
$dbCon = mysqli_connect("localhost", "root", "root", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `questions` WHERE `location` = 'wall' ORDER BY `questions`.`id` DESC ";
$query = mysqli_query($dbCon, $sql);
if ($query) {
$row = mysqli_fetch_row($query);
$hashtags = $row[2]; //instead of array('coldplay');
}
public function readTwitter(){
$dbCon = mysqli_connect("localhost", "root", "root", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `vragen` WHERE `location` = 'wall' ORDER BY `vragen`.`id` DESC ";
$query = mysqli_query($dbCon, $sql);
if ($query) {
$row = mysqli_fetch_row($query);
$accounts = $row[3];
$hashtags = $row[2];
\ORM::for_table('feed_items')->where('portal_reference', 'tw')->delete_many();
$feed = $this->twitter->getFeedByAccount($accounts);
foreach($feed as $post){
$this->twitter->savePost($post);
}
$feed = $this->twitter->getFeedByHashtag($hashtags);
foreach($feed->statuses as $post){
$this->twitter->savePost($post);
}
}
}
I have tried to combine the code and it works like I want, but I dont think this is the right way for OOP, right?
Sorry about the last post I had. Here's my revision, please help me.
<?php
//connect database
$sql = "SELECT * FROM user where user_id = 8320 AND password = 'admin' ";
$query = pg_query($sql);
var_dump($row = pg_fetch_array($query)); //dumps correctly.
?>
BUT THE PROBLEM IS THIS..when I try to make it as a function LIKE:
function check($user_id, $password)
{
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($sql);
$row = pg_fetch_array($query);
return $row;
}
AND CALL IT HERE:
var_dump($data = check(8320, 'admin')); DUMPS NULL;
How come it ended up like this?
Its returning NULL because there is an error with your SQL query, and no results are being returned. You should do some error checking in your function, try this version:
function check($user_id, $password)
{
$dbconn = pg_connect("host=localhost dbname=test");
$sql = "SELECT * FROM user where user_id = $1 AND password = $2 ";
$result = pg_query_params($dbconn, $sql, array($user_id,$password));
$row = pg_fetch_array($result);
if (!$row) {
echo pg_last_error($dbconn);
} else {
return $row;
}
}
Try the code below. It should work fine for you.
$data = check(8320, 'admin');
var_dump($data);
Seems like your PostgreSQL resource is missing inside the function. You have two options.
Declare the connection resource inside the function using global.
Establish the connection inside the function.
This is the first option:
$conn = pg_connect('host','user','pass','db');
function check($user_id, $password)
{
global $conn;
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
And this is the second option:
function check($user_id, $password)
{
$conn = pg_connect('host','user','pass','db');
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
According to the PHP manual, You may omit connection resource, but it is not recommended, since it can be the cause of hard to find bugs in scripts.
I edit my code working good but still one problem ... the data that selected from my database and displayed in my suggestion input ( only one row and last ID ) !!! How can I do it to display all data rows from my database ????
<?php
$q = strtolower($_GET["q"]);
if (!$q) return;
$host = "localhost";
$user = "root";
$password = "";
$database = "private_message_system";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
$query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($query)){
$items = array($row["user_name"] => $row["user_email"]);
}
$result = array();
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
"name" => $key,
"to" => $value
));
}
}
echo json_encode($result);
?>
As I know mysql doesn't have a array type like postgres so you have to fetch it one by one:
// here is where you get your to connection to the database
$conn = mysql_connect("your IP", "username", "password");
mysql_select_db("mydb", $conn);
// here you have to do the select to retrieve data from the table.
$query = "SELECT `name`, `to` from mytable";
// now you got all the records but you still need to iterate over this result
$result = mysql_query($query, $conn);
$array = array();
// retrieve a record and append it to the array
while($record = mysql_fetch_assoc($result)):
$array[] = $record;
endwhile;
// please close the door....
mysql_close($conn);
echo json_encode($array);
See below for a basic implementation of connecting to MySQL and searching for your $q, I've left a few comments for you to make it clearer what's going on!
<?php
// Get the query term from the url
$q = strtolower($_GET["q"]);
// Do nothing if it's empty or not set
if (empty($q)) return;
// Result array which we are going to get from MySQL
$result= array();
// Make a SQL Connection
mysql_connect("localhost", "admin", "password") or die(mysql_error());
// Try to connect to your DATABASE (change the name) or throw an error
mysql_select_db("DATABASE") or die(mysql_error());
// Get data from the "email" table
// Where the name field is LIKE the search term
$result = mysql_query("SELECT * FROM email WHERE name LIKE '%".mysqli_real_escape_string($q)."%'")
or die(mysql_error()); //throw an error if something went wrong
//Read all the results ($row) in a loop and put them in the result array
while($row = mysql_fetch_array( $result )) {
$result[] = array('name' => $row['name'], 'to' => $row['to']);
}
// Output the array as JSON
echo json_encode($result);
?>
For the more PHP experienced I am aware you can get an array from MySQL but have left it like this to make it clearer.
Enable error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);