Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am trying to assign a DB value to a PHP variable. The database is SQL. I want the database value to be $HaveOfficialPage. How can I do this?
$connection = mysqli_connect('localhost', '', '', '');
if($connection){
echo "Connected";
}
else {
die("Database connection failed");
}
$query = "SELECT HaveOfficialPage FROM vf_Category";
$result = mysqli_query($connection, $query);
if(!$result){
die("Query failed" . mysqli_error());
}
If you’re trying to iterate through the results:
while ($row = mysqli_fetch_row($result)) {
$haveOfficialPage = $row[0];
// do something with the variable
}
If you’re getting only one record:
$row = mysqli_fetch_assoc($result);
$haveOfficialPage = $row["HaveOfficialPage"];
To select a category with a condition, use prepared statements
$paths = explode("/",$_SERVER["REQUEST_URI"]);
$category = end($paths);
$query = "SELECT HaveOfficialPage FROM vf_Category WHERE category_name = ?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "s", $category);
mysqli_stmt_bind_result($stmt, $haveOfficialPage); // here we assign the result to your variable
mysqli_stmt_fetch($stmt); // fetch
echo $haveOfficialPage;
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
My SQL query is not working. Below is my code and note that in that table query worked fine and gives output. But in PHP by using mysqli_num_rows(), mysqli_fetch_assoc() and mysqli_fetch_array() all doesn't works for me.
My DB connection is :
$conn = mysqli_connect($servername, $username, $password, $db);
Note : My DB Connectivity is fine.
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$query = mysqli_query($conn, "SELECT * FROM `admin` WHERE `username`='$username'");
This query results true in PHPMyAdmin and returns false in PHP with the above functions. Can anyone answer is I made a mistake?
And I am tried that query to execute in following methods :
$row = mysqli_fetch_assoc(); // Results No Data
$data = mysqli_fetch_array($query); // Results No Data
$num = mysqli_num_rows($query); // Results 0 Data
you may execute the query before use it :
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = mysqli_query($conn , $query);
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
You mast to run mysqli_query function for receive result from DB:
$username = mysqli_real_escape_string($conn, $_POST['username']);
$query = "SELECT * FROM `admin` WHERE `username`='$username'";
$result = mysqli_query($mysqli, $query);
$row = mysqli_fetch_assoc($result);
print_r($row);
PHP MySQL sandbox here
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
to explain my question better, i have two files: dbh.inc.php
$dbServername = "localhost";
$dbUsername = "xxxxx";
$dbPassword = "secret";
$dbName = "databasename";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
mysqli_set_charset($conn,"utf8");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
$table1 = "users";//1
$table2 = "userprofile";//2
$table3 = "twofactorauth";//3
And: database-query.func.php
function selectdb($data, $values, $url) {
include ('dbh.inc.php');
extract($data);
extract($values);
switch ($data['table']) {
case '1':
$table = $table1;
break;
case '2':
$table = $table2;
break;
case '3':
$table = $table3;
break;
}
$sql = "SELECT $rows FROM $table WHERE $where;";
print_r($sql);
die();
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_close($stmt);
mysqli_close($conn);
header("Location: ".$url."?error=sqlerror");
die();
} else {
$amount = str_repeat('s', count($values));
$values = array_values($values);
mysqli_stmt_bind_param($stmt, $amount, ...$values);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$getResult = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt);
mysqli_close($conn);
$new = array_push($getResult, 'true');
return $getResult;
}
}
So the first holds database connection, and the latter has dynamic querys for insert, update and select for the moment. And i am wondering should i combine the two files, to one. Since every time i need my connect i always use one of my querys and same on the other way around?
Also 2 bonus questions: as you see in my connect file i have my table names and i use numbers in my other files and in the functions connect numbers to names.
Lastly should i use PDO, why?
To answer your question in general - yes, you can put a helper function in the same file where sql connection is made.
However, the code of your actual function is questionable at the very least. Or, to tell you truth, your function selectdb() is a torture for a programmer and shouldn't be stored anywhere. Stick to natural SQL queries written as is. You don't need numbers to represent tables. You don't need $rows variable. Everything could be written right in the SQL string. All you will need is a simple helper function that would reduce the amount of code required to run a query.
Here is an example of such mysqli include file
Once it's included in in your script, you can use it to run any mysql query, to any table, with any list of variables. Check out the following example (you can copy and paste the following code block to your file and run it as is):
<?php
require 'mysqli.php';
#Create a temporary table
$conn->query("CREATE temporary TABLE tmp_mysqli_helper_test
(id int auto_increment primary key, name varchar(9))");
# populate it with sample data
$sql = "INSERT INTO tmp_mysqli_helper_test (name) VALUES (?),(?),(?)";
$stmt = prepared_query($conn, $sql, ['Sam','Bob','Joe']);
echo "Affected rows: $stmt->affected_rows\n";
echo "Last insert id: $conn->insert_id\n";
# Getting rows in a loop
$sql = "SELECT * FROM tmp_mysqli_helper_test WHERE id > ?";
$res = prepared_query($conn, $sql, [1])->get_result();
while ($row = $res->fetch_assoc())
{
echo "{$row['id']}: {$row['name']}\n";
}
# Getting one row
$id = 1;
$sql = "SELECT * FROM tmp_mysqli_helper_test WHERE id=?";
$row = prepared_query($conn, $sql, [$id])->get_result()->fetch_assoc();
echo "{$row['id']}: {$row['name']}\n";
# Update
$id = 1;
$new = 'Sue';
$sql = "UPDATE tmp_mysqli_helper_test SET name=? WHERE id=?";
$affected_rows = prepared_query($conn, $sql, [$new, $id])->affected_rows;
echo "Affected rows: $affected_rows\n";
# Getting an array of rows
$start = 0;
$limit = 10;
$sql = "SELECT * FROM tmp_mysqli_helper_test LIMIT ?,?";
$all = prepared_query($conn, $sql, [$start, $limit])->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($all as $row)
{
echo "{$row['id']}: {$row['name']}\n";
}
As you can see, a proper helper function can keep all the flexibility and readability of SQL and reduce the amount of code at the same time.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a string called $searchquery. $searchquery contains this SQL command:
SELECT * FROM `videos` WHERE (`Title` LIKE "%query%" OR `Tags` LIKE "%query%")
How can I make MySQL execute this command from a PHP page then display the results on PHP page??
I have tried
$sql = ($searchquery)
But dosent seem to work?
Firstly you need to create database connection
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// then execute your query
$sql = "SELECT * FROM `videos` WHERE (`Title` LIKE '%query%' OR `Tags` LIKE '%query%')";
$result = mysqli_query($conn, $sql);
// and fetch result set
while($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
?>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
here's a part of my code that AFTER you submit your login credentials checks your username, password, etc...:
mysql_select_db("robur_mike") or die ("Could not find DB!");
$query = mysql_query("SELECT * FROM Bx1_Users WHERE Username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows!=0)
{
while ($row =mysql_fetch_assoc($query))
{
$dbusername = $row['Username'];
$dbpassword = $row['Password'];
$dbfirstname = $row['FirstName'];
$dblastname = $row['LastName'];
}
.....
I now need to "translate" that to run under a DB2 database in BlueMix. I am already connected to the database using the code provided here:
How to connect to a SQL Database-s2 from a .php application in BlueMix
The query should be OK since it is basic SQL. What you should change is the way you run it, since in your old code you are using the mysql library.
Looking at the other question, I assume that you are able to connect doing something like:
$conn = db2_connect($conn_string, '', '');
Now to execute the query you can use db2_exec 'translating' your code to something like:
$sql = "SELECT * FROM <schemaName>.Bx1_Users WHERE Username='$username'";
if ($conn) {
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_assoc($stmt)) {
$dbusername = $row['Username'];
$dbpassword = $row['Password'];
$dbfirstname = $row['FirstName'];
$dblastname = $row['LastName'];
}
}
db2_close($conn);
As you can see I've added a placeholder for the schema name in the SQL query. You can retrieve it within your SQL Database dashboard (Manage/Work with tables).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I can't understand how to create a prepared statement, and all tutorials I have seen was fetching only column.
My normal sql query
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM files WHERE id=$id ") or die(mysql_error());
$row = mysql_fetch_array($result);
$name = $row['name'];
$date = $row['date'];
Please show me how to create a prepared statement and how to fetch more than one column and insert the date into variables.
First of all it's not a good idea to use SELECT * in production. Instead specify needed columns explicitly. Take a look at https://stackoverflow.com/a/65532/1920232.
Now your code might look like
$id = $_GET['id'];
$db = new mysqli('localhost', 'user', 'password', 'dbname');
$sql = 'SELECT name, date FROM files WHERE id = ?'; //specify columns explicitly
if ($stmt = $db->prepare($sql)) { //create a prepared statement
$stmt->bind_param('i', $id); //bind parameters
$stmt->execute(); //execute query
$stmt->bind_result($name, $date); //bind result variables
$stmt->fetch(); //fetch values
}
$db->close();
echo $id, ' ', $name, ' ', $date;
Note: All error handling intentionally skipped for brevity.