There's a bit problem for mysqli select statement as I did a select statement which actually counts the number of results. But it does not return the value I want but instead it returns none. Need help guys. I did this select statement as a function using mysqli and php
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
echo "string</br>";
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['userssss']."asdasd</br>";
die("userssss");
$return = $row['user'];
return $return;
}
result
string
asdasd
userssss
It should show the result before asdasd
add global $con;
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as user from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['user'][0]."asdasd";
die();
$return = $row['user'][0];
return $return;
}
I found it. Silly of me.
Instead of using assoc, one must use array
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$return = $row['user'];
return $return;
}
You need to count everything meaning rows matched where clause. Also try to adopt prepared statements. Bellow code works.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function count_result($data){
$user = 'username';
$password = 'password';
$db = 'database';
$host = 'hostname';
$port = 3306;
/* Attempt MySQL server connection. Assuming you are running MySQL server */
$link = mysqli_connect($host, $user, $password, $db);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if($stmt = $link -> prepare("SELECT COUNT(*) FROM test WHERE ID= ?"))
{
/* Bind parameters, s - string, b - blob, i - int, etc */
$stmt -> bind_param("i", $data);
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($testfield1);
/* Fetch the value */
$stmt -> fetch();
$numberofrows = $stmt->num_rows;
} else{
echo "ERROR: Could not able to execute SQL. " . mysqli_error($link);
}
/* Close statement */
$stmt -> close();
echo '# rows: '. $numberofrows . PHP_EOL;
echo 'Count = '. $testfield1 ;
}
count_result(24);
?>
A silly mistake in your code :
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
echo "string</br>";
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['user']."asdasd</br>"; // did changes on this line
die("userssss");
$return = $row['user'];
return $return;
}
Related
Alright, so I have a simple database with one table, and I have a function which is supposed to get all the rows for that one table:
function get_days() {
global $db;
$query = 'SELECT * FROM days'
. 'ORDER BY idDays';
$statement = $db ->prepare($query);
$statement ->execute();
$the_days = $statement->fetchAll();
//$statement->closeCursor();
return $the_days;
//return $statement;
}
I've checked everything else, everything else functions just fine, including the part of my site where I input data into the table, that insert statement works just fine, so I've narrowed it down to this one select statement.
The problem is in you SQL syntax. You should do this:
function get_days() {
global $db;
$query = 'SELECT * FROM days '
. 'ORDER BY id';
$statement = $db ->prepare($query);
$statement ->execute();
$the_days = $statement->fetchAll();
//$statement->closeCursor();
return $the_days;
//return $statement;
}
The problem is the string concatenation of your query:
$query = 'SELECT * FROM days' . 'ORDER BY idDays';
This results in: SELECT * FROM daysORDER BY idDays
Include a space character instead:
$query = 'SELECT * FROM days' . ' ORDER BY idDays';
You can avoid problems like this with proper error handling:
try{
$statement->execute();
}
catch(PDOException $e){
exit($e->getMessage());
}
You might also want to remove the spaces in:
$db ->prepare($query);
$statement ->execute();
So they become:
$db->prepare($query);
$statement->execute();
This is simple way to select you can use a function for it.
$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 * FROM days ORDER BY idDays";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//do anything
}
} else {
echo "0 results";
}
I want to select data (at all) with PDO (always used mysqli) from an external database. It connects, and the query works on the server directly with mysql. With php, it doesn't. Here's my code:
<?php
$hostname = 'localhost';
$username = 'user';
$password = 'pass';
function testdb_connect ($hostname, $username, $password){
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
return $dbh;
}
try {
$dbh = testdb_connect ($hostname, $username, $password);
echo 'Connected to database';
} catch(PDOException $e) {
echo $e->getMessage();
}
$sql= "select * from table limit 10;";
echo "<br/>";
echo $sql;
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetchObject();
echo $row->id;
It shows "connected to database", and the "echo $sql" part, but doesn't display any information.
Your first part of the question have been solved.
now this
I now want to print the 10 rows instead of just the first one. How do
I do it?
The are many ways you can do that, but you need to loop through your results and display the desired Rows
Option 1
$sql = $dbh->query("SELECT * from table limit 10")->fetchall(PDO::FETCH_ASSOC);
foreach($sql as $row){
// print_r($row); // see them all
echo $row['desiredRow']; //print them one by one
}
Option 2
$sql = $dbh->query("SELECT * from table limit 10");
while($row=$sql->fetch()){
// print_r($row);
echo $row['desiredRow'];
}
Option 3
<?php
$sql = "SELECT * from table limit 10";
$stmt = $dbh->prepare($sql);
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){//check results
foreach($results as $row){
print_r($row);
}
}else{
echo "no results found";
}
?>
I've got a problem with my PHP Registration Script that firstly checks, if the user exists.
It always outputs "false".
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$database = #mysql_connect("***********", "********", "******") or die("Can't connect to the server. Error: ".mysql_error());
//$username = mysql_real_escape_string($username);
$passwort = hash("sha256", $passwort);
$numrows = mysql_query("SELECT * FROM *******.mikgames WHERE username='".$username."' LIMIT 1");
$checkuserexists = mysql_num_rows($numrows);
if($checkuserexists==0) {
$abfrage = mysql_query("INSERT INTO *******.mikgames (username,passwort) VALUES ('$username', '$passwort')");
echo'true';
}
else {
echo'false';
}
?>
Edit: Now I'am using MySQLi and I've changed the code into this:
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$con = mysqli_connect('************','******','******') or die(mysqli_error());
mysqli_select_db($con, "*******") or die("cannot select DB");
$passwort = hash("sha256", $passwort);
$query = mysqli_query($con,"SELECT * FROM *******.mikgames WHERE username='".$username."'");
$result = mysqli_num_rows($query);
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames (username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
echo 'true';
}
else {
echo 'false';
}
?>
And it works.
You could go one step better and take an OOP approach using the PDO driver; PDO invokes security by allowing secure parameter binding and uses the SQL preferred functions.
Inside your pdo_driver.php file:
namespace ProjectName\App\Drivers;
if(!defined('IN_PROJECTNAME'))
{
die('No Script Kiddies Please...');
}
interface EntityContainer
{
public function query($statement, array $values = array());
}
class Entity extends \PDO implements EntityContainer
{
public function __construct(
$dsn = 'mysql:host=XXXX;dbname=XXXX', $user = 'XXXX', $pass = 'XXXX'
) {
try {
parent::__construct($dsn,$user,$pass);
} catch (PDOException $ex) {
die('FATAL ERROR: ' . $ex->getMessage());
}
}
public function query(
$statement, array $values = array()
) {
$smpt = parent::Prepare($statement);
(empty($values)) ? $smpt->execute() : $smpt->execute($values);
return $smpt;
}
}
Inside any other php file:
define('IN_PROJECTNAME', 0);
require_once dirname(__FILE__) . '/path/to/pdo_driver.php';
$container = array();
$container['Connection'] = new ProjectName\App\Drivers\Entity();
$username = $_GET['username'];
$passwort = $_GET['passwort'];
if(empty($container['Connection']->query('SELECT passwort FROM ******.mikgames WHERE username = ?', [$username])->fetch()['passwort'])) {
$container['Connection']->query('INSERT INTO ******.mikgames (username,passwort) VALUES (?, ?)', [$username,$passwort]);
}
Two Factors:
Firt Factor
You need to add an error output for debugging purposes:
$query = mysqli_query($con,"SELECT * FROM <tablename> WHERE
username='".$username."'") or die(mysqli_error($con));
I can't see a clear error with the information you have displayed here so far so you should also check what the value of $username acutally is and how closely it fits the value in the DB. Also read and take on board what the error output tells you.
Second Factor:
Your problem is you're running/articulating a query twice, here:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
You see $abfrage is a MySQL result object and you're then plugging it back into a MySQL query call, with the variable declaration $result. So your result is querying a query. This is an error.
What you probably want to do is use MySQLi_affected_rows to count how many rows have been inserted and run the appropriate IF clause:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_affected_rows($con);
echo 'true';
}
else {
echo 'false';
}
Use #mysql_***** for your ptoject.
$sql="SELECT * FROM table_name";
$result=#mysql_query($sql, $conn);
while ($name = # mysql_fetch_array($result)){
echo $name ['username'];
}
You just used simple mysql_***
I have already had some help but not sure why this isn't working.
I am trying to use a form to let a user filter their activity (which is stored in a DB)
My code:
$_GET['from'] = '01/11/2013';
$_GET['to'] = '25/11/2013';
$from = DateTime::createFromFormat('d/m/Y', $_GET['from']);
$to = DateTime::createFromFormat('d/m/Y', $_GET['to']);
$sql = "
SELECT * FROM transfer
WHERE personID = $user AND DATE(time) BETWEEN '%s' AND '%s'
";
$sql = sprintf($sql, $from->format('Y-m-d'), $to->format('Y-m-d'));
print_r($sql);
This prints
SELECT * FROM transfer WHERE personID = 84587749 AND DATE(time) BETWEEN '2013-11-01' AND '2013-11-14'
When I query this in PHPmyadmin it shows the record, however not showing in my page?
The SQL looks fine but you don't appear to have issued the executed the SQL query in the database and retrieved the results?? Maybe I'm missing something but you need to connect to your database:
class DBi {
public static $mysqli;
}
DBi::$mysqli = new mysqli('servername', 'database', 'password', 'user');
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
Then you need to perform the query:
$result = DBi::$mysqli->query($sql) or die ("Unable to execute SQL command:".$sql);
And finally, retrieve and use the result:
$row = $result->fetch_assoc();
echo $row["fieldname"];
Here is an example how you print out your results.
$dbserver = "localhost";
$dbname = "nameofDB";
$dbusername = "username";
$dbpassword = "password";
$mysqli = new mysqli($dbserver, $dbusername, $dbpassword, $dbname);
$query = "SELECT * FROM transfer WHERE personID = 84587749 AND DATE(time) BETWEEN ? AND ?";
if($stmt = $mysqli->prepare($query)){
/*
Binds variables to prepared statement
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
$to = $_POST['to'];
$from = $_POST['from'];
$stmt->bind_param('ss', $from, $to);
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Configure this how you want to print out each row.
echo 'Details: '.$row['details'].'<br>';
echo 'Time: '.$row['time'].'<br>';
echo 'Balance: '.$row['balance'].'<br>';
echo '<br><br>';
}
/* free results */
$stmt->free_result();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
To make sure my database is secure I'm using prepare statements. Here is my code:
//connecting to MySql database
$con=mysqli_connect("host","user","pass","dbname");
// checking database connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_prepare($con,"SELECT * FROM `table` WHERE emb=? LIMIT 1");
mysqli_stmt_bind_param($stmt, 's', $emb);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
Now I want to know how can I use ASSOC fetch array
$embInfo = mysqli_fetch_array($stmt, MYSQLI_ASSOC);
I want this so that I can just put something like below to get values
$embInfo['name']
and
$embInfo['email']
try this:
//connecting to MySql database
$con=mysqli_connect("host","user","pass","dbname");
// checking database connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_prepare($con,"SELECT * FROM `table` WHERE emb=? LIMIT 1");
mysqli_stmt_bind_param($stmt, 's', $emb);
mysqli_stmt_execute($stmt);
while($embInfo = mysqli_fetch_array($stmt, MYSQLI_ASSOC)){
echo 'My name is '.$embInfo['name'].'and my email is '.$embInfo['email'].'<br/>';
}
mysqli_stmt_close($stmt);
May i suggest an alternative
{
$server = '';
$user = '';
$pass = '';
$db = '';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
$club=$_POST'club'];
$sql = "SELECT * FROM players WHERE club = '$club'";
$result=mysqli_query($mysqli,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['player'];
}
}