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?
Related
I cannot get my Mysqli queries to both work. If I comment out one function in my html, the other function is properly executed and vice versa.
function all_posts() {
require_once 'database.inc.php';
$mysqli = mysqli_connect($host, $username, $password, $database);
$query = mysqli_query($mysqli, "SELECT variable_name, post_name, post_date, post_display FROM blog_posts ORDER BY id DESC LIMIT 5");
if (!$query)
echo mysqli_error();
while ($results = mysqli_fetch_assoc($query)) {
$post_name = $results['post_name'];
$post_date = $results['post_date'];
$post_display = $results['post_display'];
$variable_name = $results['variable_name'];
echo "<a href='posts.php?post={$variable_name}'>";
echo "<div class='entry'>";
echo "<div class='entry_header'>";
echo "<h2>{$post_name}</h2>";
echo "<h3>{$post_date}</h3>";
echo "</div>";
echo "<p>{$post_display}</p>";
echo "</div>";
echo "</a>";
}
mysqli_free_result();
}
function all_sidebar_posts() {
require_once 'database.inc.php';
$mysqli = mysqli_connect($host, $username, $password, $database);
$query = mysqli_query($mysqli, "SELECT variable_name, post_name FROM blog_posts ORDER BY id DESC LIMIT 5");
while ($results = mysqli_fetch_assoc($query)) {
$post_name = $results['post_name'];
$variable_name = $results['variable_name'];
echo "<li><a href='posts.php?post=$variable_name'>$post_name</a></li>";
}
mysqli_free_result();
}
Here is the html that I am outputting to.
<ul>
<?php all_sidebar_posts(); ?>
</ul>
</div>
<div class="content_container">
<?php all_posts(); ?>
</div>
I have tried using mysqli_data_seek(); but haven't had luck. Perhaps I am not using it right? I have browsed many questions and found similar ones but I have tried them all to no avail. I am new to programming so I may be overlooking something basic. Thank you all for the help!
You are doing it wrong way.
Never mix your data manipulation code with presentation code.
First, get the posts into array:
require_once 'database.inc.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect($host, $username, $password, $database);
$sql = "SELECT variable_name, post_name, post_date, post_display
FROM blog_posts ORDER BY id DESC LIMIT 5"
$result = mysqli_query($mysqli, $sql);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
and then use this $data array to display posts any times you need, simply using foreach()
http://www.php.net/manual/en/mysqli-result.data-seek.php
Consult the manual for the usage of data_seek();
Take this example:
$Query = "SELECT * FROM Users WHERE ID='1'";
$TheQuery -> $MySQLi->query($Query);
$Results = $TheQuery->fetch_array(MYSQLI_ASSOC);
$TheQuery->data_seek(0); // Lets you re-use the query
$Count = $TheQuery->num_rows; // Gets the count
so in your case:
You should perform the procedure method:
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($result = mysqli_query($link, $query)) {
/* fetch row */
$row = mysqli_fetch_row($result);
printf ("City: %s Countrycode: %s\n", $row[0], $row[1]);
mysqli_data_seek($result, 0);
$row_cnt = mysqli_num_rows($result);
/* free result set*/
mysqli_free_result($result);
}
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'];
}
So I installed this jackpot script with a layout and everything and within the jackpot script there was a set.php file which I tried to set up, it looked like this:
<?php
$sitename = "csgoxd.net";
$link = #mysql_connect("localhost:3306", "csgoxdne", "thisisasecretpassword");
$db_selected = mysql_select_db('csgoxdne_csgoxddb', $link);
mysql_query("SET NAMES utf8");
function fetchinfo($rowname,$tablename,$finder,$findervalue) {
if($finder == "1") $result = mysql_query("SELECT $rowname FROM $tablename");
else $result = mysql_query("SELECT $rowname FROM $tablename WHERE `$finder`='$findervalue'") or die (mysql_error());
$row = mysql_fetch_assoc($result);
return $row[$rowname];
}
?>
So I'm new when it comes to coding in general (I know some basic stuff but that's it) so basically I'm not sure if I'm supposed to fill out more of this file because I get this error on my website.
"Table 'csgoxdne_csgoxddb.info' doesn't exist"
I'm new to this and I'm trying to learn so help is much appreciated.
You should use MySQLi to make use of its advantages it offers over MySQL. You can see more here.
The script you have isn't all too bad, but it does need some tweaking. It's vulnerable to injection like Marc B said. I'm going to assume that csgoxdne_csgoxddb is your table name.
Try this:
<?php
$mysqli = new mysqli("localhost:3306", "csgoxdne", "thisisasecretpassword");
if (mysqli -> error){ print ("Error connecting! Message: ".$mysqli->error); }
mysqli_set_charset($mysqli, 'utf8');
function fetchinfo($rowname, $tablename, $finder, $findervalue) {
if ($finder == "1") {
$query = "SELECT * FROM $tablename WHERE rowname = '$rowname'";
$result = mysqli_query($mysqli, $query);
} else {
$query = "SELECT * FROM $tablename WHERE `$finder`='$findervalue'";
if (!$query) {
die('Invalid query: ' . $mysqli->error);
}
$result = mysqli_query($mysqli, $query);
}
return $result;
}
?>
Oh and make sure the port number on your localhost is correct.
Also to go through the values of result you can use:
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
#do things
}
}
So I have a SQL database with a number of objects in that contain name price and images, I would like to know how I can select them using php and output the result into json
<?php
$db = mysqli_connect ('localhost', 'root', '', 'car_rental') or die ("SQL is Off");
$car = (isset($_GET['car']) ? $_GET['car'] : null);
mysqli_select_db($db,"car_rental");
$SQL = "SELECT * FROM `products` WHERE name LIKE \'%$car%\'";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
print $db_field['sku'] . "<BR>";
print $db_field['name'] . "<BR>";
print $db_field['img'] . "<BR>";
print $db_field['price'] . "<BR>";
}
?>
This is my current code car variable will change dependent on car selected
thanks
For getting all values in json format, you need to use like that:
<?
$newArr = array();
while ( $db_field = mysql_fetch_assoc($result) ) {
$newArr[] = $db_field;
}
echo json_encode($newArr); // get all products in json format.
?>
UPDATE 1:
You are mixing mysqli extension with mysql. Change mysql into mysqli
UPDATE 2:
Why are you connecting database twice in code?
Modified Code:
<?php
$link = mysqli_connect("localhost", "root", "", "car_rental");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$car = (isset($_GET['car']) ? $_GET['car'] : null);
$query = "SELECT * FROM `products` WHERE name LIKE '%$car%'";
if ($result = mysqli_query($link, $query)) {
$newArr = array();
/* fetch associative array */
while ($db_field = mysqli_fetch_assoc($result)) {
$newArr[] = $db_field;
}
echo json_encode($newArr); // get all products in json format.
}
?>
Side Note:
Also on PHP error reporting in development phase for saving your time.
For the past two days or so I've been converting my functions to mysqli. I've run into a problem. I have a function that returns an array containing a row from the database. However, I want the array to contain multiple rows versus one. Also, how would I be able to echo out the individual posts. Here is my failed attempt that only displays one row in the array.
$mysqli = new mysqli("localhost", "user", "password", "database");
function display_posts ($mysqli, $user_id) {
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
$user_id = (int)$user_id;
$query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id
LIMIT 4";
if ($result = $mysqli->query($query)) {
$row = $result->fetch_assoc();
return $row;
$result->free();
$stmt->close();
}}
Here I am trying to display the data.
$user_id = 1;
$posts = display_posts($mysqli, $user_id);
//Not sure what to do with $posts. A While loop perhaps to display each post?
You have to use a loop to get them all at once:
<?php
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4';
$result = $mysqli->query($query);
$rows = resultToArray($result);
var_dump($rows); // Array of rows
$result->free();
Why not use directly like this:
$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);
I'm late, but I believe this is what you wanted to achieve:
$mysqli = new mysqli("localhost", "user", "password", "database");
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
function display_posts () {
global $mysqli;
global $fields;
$query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4";
$posts = $mysqli -> query($query) or die('Error: '.$mysqli -> error);
if ($posts -> num_rows > 0) {
while ($row = $posts -> fetch_assoc()) {
$value = $row['/*The table column here (You can repeat this line with a different variable e.g. $value 2, $value 3 etc and matching them with the respective table column)*/'];
echo $value./*Concatenate the other variables ($value 1 etc) here*/'<br />';
}
}else {
echo 'No records found.';
}
}
//Call the function
display_posts ();