How to use variables in mysql table with PHP - php

I am a beginner of the program.
I am trying to use a PHP variable written in a MySQL table, but it is not recognized as a variable in PHP.
I made a table to test using this code
CREATE TABLE test_table (
'id' INTEGER,
'col_1' TEXT
);
And insert data;
INSERT INTO test_table VALUES('1', '$var');
I`ve tried to test using simple PHP code;
<?php
$server = 'localhost';
$user = 'root';
$password = '1111';
$database = 'test_database';
$conn = mysqli_connect($server, $user, $password, $database);
$sql = "SELECT * FROM test_table";
$table = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_assoc($table)) {
$var = 1;
echo $rows['col_1'];
}
?>
I expected the result will be '1' but actual result was '$var'.
How can MySQL data be recognized as a PHP variable?

Instead of using
echo $rows['col_1'];
use like this
$result=$query->result_array();
echo $result;

Related

How to fix non response mysql connection in PHP

I am trying to get a variable from a mySQL table into my PHP code. I am using a mysqli_query command. When I try to echo the result, it echos nothing, not even other echo statements.
I have ensured that the $conn is correct and working, and that the Sql query is correct by running it directly in PHPmyAdmin.
<?php
session_start();
include_once("includes/dbh.inc.php");
$UID = $_POST['userIdVariable'];
$UID = $_SESSION['u_uid'];
$balance = "SELECT account_balance FROM `users` WHERE user_uid = \"$UID\"";//this line probably works
$result = mysqli_query($conn, $balance);
echo "$result";
When I run this code it would output nothing. The right side of the $balance line is a good sql query according to PHPmyadmin. The $UID variable is read in correctly.
You need to use mysqli_fetch function to get result columns out of $result object.
while ($data = mysqli_fetch_assoc($result)) {
printf("%s \n", $data["account_balance"]);
}
Don't use quotation in a field name or table name inside the query.
$balance = "SELECT account_balance FROM users WHERE user_uid = '$UID'";
please check your database connectivity.there could be something missing like database name.
and print your $UID. may be there is no id getting.
to print data use print_r();
and try this:
session_start();
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password,"databasename");
$UID=1;
$balance = "SELECT account_balance FROM users WHERE user_uid =$UID";
$result = mysqli_query($conn, $balance);
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['account_balance'];
}
}

Double or more value inserted when insert query written inside another query result object

I have the code below which was written in php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * from table name";
$result = $conn->query($sql);
//the result count is 95142
while($row = $result->fetch_assoc()) {
$sql = "insert into table1 (column) values ('test')";
$result = $conn->query($sql);
}
$conn->close();
?>
Which inserting more than 100 000 data in table1 but if I try to limit the source query up to 30 000 it inserts correct count of data into table1.
i.e
$sql = "SELECT * from table name limit 10000";
Both the table are in same Database.
Even tried with mysql_connect & mysql_query() method also getting the same error. Also tried with another connection for insert query but issue exists.
If I try the code like this
$flag = 1;
while($row = $result->fetch_assoc()) {
$flag = $flag + 1;
}
echo $flag;
I am getting the result of 95142.
you must really use different variable names in the second query !!!
while($row = $result->fetch_assoc()) {
$sql2 = "insert into table1 (column) values ('test')";
$result2 = $conn->query($sql2);
}
and secondly, delete the previous rows before running script, and then check the count, it must work fine.
Change your variable name $result inside the while.
Ex:
while($row = $result->fetch_assoc()) {
$insertSQL = "insert into table1 (column) values ('test')";
$insertRow = $conn->query($insertSQL);
}
The value of $result has been changed when insert query is executed. Maybe this is main problem.

Mysql Fetch not working

i really dont know why this code isnt working.. database connection works, the timestamp is written to the database.
But i cant figure out why i get a blank page with this code here (i should see the timestamp as echo).
Anyone an idea about this ?
Thank you!
<?php
$user = "daycounter";
$password = "1234";
$database = "daycounter";
$host = "localhost";
$date = time();
// Create connection
$conn = new mysqli($host, $user, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Error: " . $conn->connect_error);
}
//Insert timestamp in database
$sql = "INSERT INTO datum (datum)
VALUES ('".$date."')";
//check if that worked
if ($conn->query($sql) === TRUE) {
echo "That worked!";
}
//get timestamp from db and display it as echo
$select = "SELECT 'datum' FROM 'daycounter'";
$result = mysql_query($select);
while($row = mysql_fetch_object($result))
{
echo "$row->datum";
}
?>
You're using a mysqli DB connection, but calling mysql to do your select. You cannot mix/match the database libraries like that. If you'd had even minimal error checking, you'd have been told that there's no connection to the db:
$result = mysql_query($select) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^
Plus, your select query has syntax errors. 'daycounter' is a string literal - you cannot select FROM a string. 'datum' would be syntactically correct, you can select a string literal from a table, but most like you want:
SELECT datum FROM daycounter
or
SELECT `datum` FROM `daycounter`
Neither of those words are a reserved word, so there's NO need to quote them, but if you're one of those people who insist on quoting ALL identifiers, then they must be quoted with backticks, not single-quotes.
$select = "SELECT 'datum' FROM 'daycounter'";
$result = mysqli_query($conn, $select);
while($row = mysqli_fetch_object($result)) {
echo "$row->datum";
}

mysql_query() not taking php variables

I'm passing a variable to a mysql query, $name is a variable that is getting a decrypted string. It is later passed to the SEARCH query. $name has a name in it (which i have seen via an echo).
The SEARCH query just wont take this variable. If i quote the string that is present in the SQL table, i do get an output (count as 1). I cant see where the problem is, because the same code is working in another file (its taking a variable in its query from an HTML entry though), and its embarrassing!
$decrypted_text1 = mcrypt_ecb(MCRYPT_DES, $key_value, $encrypted_text1, MCRYPT_DECRYPT);
$name = $decrypted_text1;
$username = "root";
$password = "speaker1";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_selectdb("login", $dbhandle);
$query = "SELECT * FROM users WHERE Username='$name' ";
$result = mysql_query($query, $dbhandle) or die(mysql_error());
$count5 = mysql_num_rows($result);
Delete the quotation marks around the variableit should look like this:
$query = "SELECT * FROM users WHERE Username=$name ";

PHP Select fields from database where username equals X

im having problems in PHP with selecting Infomation from a database where username is equal to $myusername
I can get it to echo the username using sessions from the login page to the logged in page.
But I want to be able to select things like 'bio' and 'email' from that database and put them into variables called $bio and $email so i can echo them.
This is what the database looks like:
Any ideas?:/
You should connect to your database and then fetch the row like this:
// DATABASE INFORMATION
$server = 'localhost';
$database = 'DATABASE';
$dbuser = 'DATABASE_USERNAME';
$dbpassword = 'DATABASE_PASSWORD';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($X);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM table_name WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio = $row['bio'];
$email = $row['email'];
Note 1:
Dont Use Plain Text for Passwords, Always hash the passwords with a salt
Note 2:
I used MYSQL_QUERY for your code because i don't know PDO or Mysqli, Escaping in MYSQL is good enought but Consider Using PDO or Mysqli , as i don't know them i can't write the code with them for you
Simplistic PDO examples.
Create a connection to the database.
$link = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Use the $link variable when creating (preparing) and executing your SQL scripts.
$stmt = $link->prepare('insert into `history` (`user_id`) values(:userId)');
$stmt->execute(array(':userId' => $userId));
Code below will read data. Note that this code is only expecting one record (with 2 data elements) to be returned, so I'm storing whatever is returned into a single variable (per data element), $webId and $deviceId.
$stmt = $link->prepare('select `web_id`, `device_id` from `history` where `user_id` = :userId');
$stmt->execute(array(':userId' => $userId));
while($row = $stmt->fetch()) {
$webId = $row["web_id"];
$deviceId = $row["device_id"];
}
From the picture I can see you are using phpMyAdmin - a tool used to handle MySQL databases. You first must make a connection to the MySql server and then select a database to work with. This is shown how below:
<?php
$username = "your_name"; //Change to your server's username
$password = "your_password"; //Change to your server's password
$database = "your_database" //Change to your database name
$hostname = "localhost"; // Change to the location of your server (this will prolly be the same for you I believe tho
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select examples");
?>
Then you can write something like this:
<?php
$bio = mysql_query("SELECT bio FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
and
<?php
$email = mysql_query("SELECT email FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
Where *your_database_table_name* is the table in the database you selected which you are trying to query.
When I was answering your question, I was referencing this site: http://webcheatsheet.com/PHP/connect_mysql_database.php. So it might help to check it out as well.

Categories