Check For Existing Table Using variable - php

I was wondering how to incorporate a variable into a PHP statement to check if a table exists. For some reason the query does not accept the variable. Here is what I have:
<?php
$servername = "localhost";
$username = "***";
$password = "***";
$dbname = "stavacom_students";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = "1";
echo $id;
$query101 = 'select 1 from "$id" LIMIT 1';
$val = mysqli_query($conn, $query101);
if($val !== FALSE){
echo "no";
} else {
?>
what?
<?php
};
?>

The statement needed a tilde around the variable. Here is the final statement:
$query101 = "select 1 from `$id` LIMIT 1";

You can implement this in two ways using mysql, the first one being a simple SELECT FROM type of query:
<?php
function mysql_table_exists(mysqli $conn, $table)
{
$res = #$conn->query('SELECT 1 FROM `' . $conn->real_escape_string($table) . '`');
if($res)
{
$res->free();
return true;
}
return false;
}
?>
You can also do this by performing a check in the INFORMATION_SCHEMA using the following statement:
SELECT 1 FROM information_schema.tables WHERE table_schema = '<database name>' AND table_name = '<table name>' LIMIT 1;
Lastly, you can call SHOW TABLES LIKE '<table name>'; and parse the results for a match, similar to the concept in the first example.

Use double quote("...Query...") Edit your query
$query101 = 'select 1 from "$id" LIMIT 1';
Into
$query101 = "select 1 from '".$id."' LIMIT 1";
OR
$query101 = "select 1 from $id LIMIT 1";

Change this, hope it work
$query101 = 'select 1 from "$id" LIMIT 1';
to this
$query101 = 'select 1 from "'.$id.'" LIMIT 1';

Related

Error Using mysqli_data_seek when using Do While Procedure [duplicate]

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);
}

Group By Not working - only displaying 1st entry

I have over 40'000 entries and each is assigned to a "list_name"
I am basically trying to get just the list_name value echo'd out
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
$groupr = mysqli_fetch_assoc($groupq);
do {
echo $groupr['list_name'];
} while($groupr = mysqli_fetch_assoc($groupq));
however its only displaying 1 entry then no more ..
https://imgur.com/a/3rnXGet
Try this.
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
while($groupr = mysqli_fetch_assoc($groupq)){
echo $groupr['list_name'];
}
$database = "sample" //replace your database name here
$conn=new mysqli("localhost","root","",$database); // here username is root and password is null , change it according to yours
if($conn->connect_error)
{
echo $conn->connect_error;
die("sorry database connection failed");
}
$sql = "SELECT * FROM products-full GROUP BY list_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row['list_name'];
}
}
thats it
try this
$groupq = mysqli_query($dbc, "SELECT list_name, count(*) FROM `products-full` GROUP BY
`list_name`");
while($groupr = mysqli_fetch_assoc($groupq)) {
echo $groupr['list_name'];
}

Use data from one SQL-query to another

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'];
}

php's mysqli_multi_query not working

I've been trying to execute a multiple query, so I've searched for a better approach on how to do this and I've read this mysqli_multi_query in php.
I tried it on my own to see the results, but it keeps on giving me error. Here's the code:
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '".$studid."'";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'";
if (mysqli_multi_query($conn, $sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
With the code above, it will just print error from the else statement I set. I also tried changing the second query to $sql .= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'"; and also tried putting semicolon after the first query to tell the SQL that I'm done with the first query since I'm putting 2 strings together, but still no luck.
try this
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '$studid';";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '$classcode'";
if ($conn->multi_query($sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
Make one query instead of two :
"SELECT ts.*, tc.*
FROM tbl_students as ts, tbl_classes as tc
WHERE ts.stud_id = '$studid'
AND tc.class_code = '$classcode'"
Note : If you get redundant data then use group by.

PHP & MYSQL: Select from where id=$id

So I'm making a usergroup function that allows me to block off pages to lower user levels. This is my function for grabbing info:
function grab_info($id, $requested_info){
$id = $_SESSION['user_id'];
$requested_info = $requested_info;
$con = new mysqli('localhost', 'root', '', 'login');
if ($con->connect_errno >0){
die("Handle your connection error here");
}
$sql = "SELECT * FROM `users` WHERE `id` = $id";
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
while($row = $result-fetch_assoc()){
$info = $row[$requested_info];
return $info;
}
}
Right here:
$sql = "SELECT * FROM `users` WHERE `id` = $id";
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
is where something is going wrong. This is my method for grabbing the info:
$id = $_SESSION['user_id'];
$rank = grab_info($id, 'rank');//Gets rank from our id
$meets = can_access($rank, 4, true);//We're saying our user has a rank of 1 to access this page you need a rank of 3 and only 3 hence strict
if ($meets == false){//user cant access page
header("Location: index.php");
die();
}
Basically, it just keeps giving me the "There as a query error for some reason handle your query error" and I'm stuck. New to php so sorry if it's messy.
Using prepared statements and cast the variable as an integer.
$stmt = $con->prepare("SELECT * FROM `users` WHERE `id` = ?");
$stmt->bind_param("i",$id);
$id = (int) $_SESSION['user_id'];
$stmt->execute();
$result = $stmt->get_result();
Check to make sure that $id is actually set. If it's null that will cause your query to explode.
$sql = "SELECT * FROM `users` WHERE `id`='{$id}'";
Try this :)
$query=mysql_query("SELECT * FROM user WHERE user_email='$user_email');
Please try this:
function grab_info($id, $requested_info){
$id = $_SESSION['user_id'];
$requested_info = $requested_info;
$con = new mysqli('localhost', 'root', '', 'login');
if ($con->connect_errno >0){
die("Handle your connection error here");
}
$sql = "SELECT * FROM users WHERE id =". $id;
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
while($row = $result->fetch_assoc()){
$info = $row;
return $info;
}
}

Categories