How do I write a JSON_TABLE query in php? - php

I am running this query in phpmyadmin (mysql 8.0.13):
SELECT people.* FROM product, JSON_TABLE(attributes, '$.people[*]' COLUMNS (firstname VARCHAR(40) PATH '$."firstname"')) people
It works as expected but when I try the same query in php nothing works.
$result = mysqli_query($conn, "SELECT people.* FROM product, JSON_TABLE(attributes, '$.people[*]' COLUMNS (firstname VARCHAR(40) PATH '$."firstname"')) people");
while($row = mysqli_fetch_assoc($result))
{
$firstname = $row['firstname'];
}
Can someone please tell me what I am doing wrong?

$result = mysqli_query($conn, "SELECT people.* FROM product, JSON_TABLE(attributes, '$.people[*]' COLUMNS (firstname VARCHAR(40) PATH '$.firstname')) people");
You had a syntax error in your query. You mixed double and single quotes in the firstname. Give a try to the above query and let me know if it works.

Related

Replace variable with query

I am pretty new to using mysql and variables in php.
I have this code
mysql_query("INSERT INTO `forum_threads` (`name`, `byid`, `cid`,
`content`, `time`, `lastreplied_time`, `lastreplier_id`) VALUES
('{$title}', '{$uid}', '{$cid}', '{$content}', '" . time() . "', '" .
time() . "', '{$uid}');") or die(mysql_error());
In my php file, I want byid to be the value of id in my table forum_users. So can I replace {$uid} with something that will get the value from forum_users. Because I don't think {$uid} is working correct.
I found this code
/* Non-existant forum account */ final public function
createForumAccount($uid) {
$getHabboUser = mysql_query("SELECT * FROM
`users` WHERE `id` = '{$uid}' LIMIT 1");
I assume that the function of that code is to get the {$uid} equal the id from the users table, I want to make the {$uid} to equal the id from the forum_users table.
Then I found this code:
final public function getUserData($uid, $var) {
if($this->checkForAccount($uid) == true) {
$check = mysql_query("SELECT `{$var}` FROM `forum_users` WHERE `uid` = '{$uid}' LIMIT 1") or die(mysql_error());
return mysql_result($check, 0);
}
}
That code wants the {$uid} to equal forum_users id. And that is exactly what I want, but it doesn't equal that, it equals the id from the users table instead, I assume it might collide with eachother or something.
How can I solve this? Can I replace {$uid} in my first code, so byid is selected instantly from forum_users? Can I make a new variable that equals forum_users.id?
First of all this sql query makes no sense. However I am also not sure your question either. If your wanting to change byid to id in your table then you must alter the table. But here is a cleaner version of your sql query.
try:
mysql_query("INSERT INTO forum_threads SET name=\"".$title."\",byid=\"".$uid."\",cid=\"".$cid."\",content=\"".$content."\",time=\"".time()."\",lastreplied_time=\"".time()."\",lastreplier_id=\"".$uid."\" WHERE id=\"".$uid."\" LIMIT 1") or die("Error: ".mysql_error());
//You Change ID to byid
to change byid to ID
mysql_query("ALTER TABLE `forum_threads` CHANGE `byid` `id` int NOT NULL")or die("Error: ".mysql_error());
// this will change the column byid to id
Just Remember Mysql_connect() and mysql API are old and not used after php 7 so start to learn mysqli api
http://php.net/manual/en/book.mysqli.php

mysqli_fetch_array() expects parameter 1 to be mysqli_result, in some column selected

I'm trying to select all of my column and it works perfectly with this
$query = "SELECT * FROM employee";
$result = mysqli_query($con, $query);
while ($employee = mysqli_fetch_array($result)) {
# code...
print (json_encode($employee));
}
and I also succeed select some of my column using this code
$query = "SELECT ID, NAME, LAT FROM employee";
$result = mysqli_query($con, $query);
but I failed when I try to select LONG column, it said that
mysqli_fetch_array() expects parameter 1 to be mysqli_result
It just show when I select LONG column, but it works well if I select another column.
"But i failed when i try to select LONG column"
That's because LONG is a MySQL reserved word.
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Either wrap it in backticks, or choose another word for it.
I.e.:
$query = "SELECT ID, NAME, `LONG` FROM employee";
or
$query = "SELECT ID, NAME, LAT, `LONG` FROM employee";
LONG is a MySQL reserved word. So, your query is resulting in syntax errors when you run mysqli_query(). To get around that problem, put it in backticks, like this:
$query = "SELECT ID, NAME, LAT, `LONG` FROM employee";
$result = mysqli_query($con, $query);

No getting result from query on host database

On my test machine the query for finding a users last_name and id works fine. I cannot figure out why it will not work on my host.
For this table
students(
id VARCHAR(5) NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
grade SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (id)
);
I run this query and there is no problem.
$sql="SELECT * FROM $tbl_name WHERE last_name ='$myusername' and id ='$mypassword'";
$result = #mysqli_query ($dbc, $sql);
mysqli_close($dbc);
if(!is_object($result) || $result->num_rows != 1)
{
$errors[] = 'No entries found, maybe capitalize your last name.';
}
else
{
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['username'] = $_POST['username']; //last name
$_SESSION['firstName'] = $row['first_name'] ;
}
On the host though, there is no rows in the result.
However, I ran this set of code and all the entries show up. Why does the query not work?
$sql="SELECT * FROM $tbl_name";
$num_results = mysqli_num_rows($result);
for ($i=0; $i<$num_results; $i++)
{
$row = mysqli_fetch_assoc ($result);
print stripslashes($row['last_name'])." ".stripslashes($row['id']);
}
By the way, the username is a persons last name and their password is their id. I am not that experienced with PHP and MySql, but this logically does not make sense to me.
Should be using mysqli_query.
Just please be sure to change $link with the connection result (of mysqli_connect).
Code:
$sql = "SELECT * FROM $tbl_name";
$result = mysqli_query($link, $sql);
$num_results = mysqli_num_rows($result);
$i = 0;
while ($row = mysqli_fetch_assoc ($result)) {
print stripslashes($row['last_name'])." ".stripslashes($row['id']);
$i++;
}
I am not sure about it, but I think you're using the wrong language for a mysql host, for example the loop isn't supposed to be in SQL language. As far as I know, this looks like C or C++ (it could depend of what kind of database you're currently using).
But what you need to know is that with this query you need to know the exact name and the exact password. Just in case, do this.
The query in SQL language, should be written it as it follow :
SELECT * FROM students WHERE last_name = "ifyouknowit" OR password="ifyouknowit";
You'll be sure to have at least one result, and it would show up the whole concerned lines as you're calling the " * ". So you don't really need a parameter, as the password is supposed to be unique to everyone.. (Theorically).
In another case, try to add one more column and call it USERID or something like this, to set a unique referent number. So you'll be sure not to be confusing between two people having the same name and last name which could happen easily.
Also, be sure to use the write syntax correctly about the name (like the capital letters are important somehow).
And I notice also that you don't have any password column in this table. Where is it stored? In anycase, with this query you'll still have results.
"students(
id VARCHAR(5) NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
grade SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (id)
);"
You should call the password database from where it's stored. Put more informations about the other tables and then I'll write a complete query for you.
This code was clearing the variables values so nothing was being searched for in the query. I thought this was standard code that should be used, apparently not.
//prohibit sql injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

mysql_num_rows() is not returning properly value

After a search here I couldn't see anyone with the same (strange) problem as me.
I have a very simple task which is to check whether some name already exists on a table, but the thing is the mysql_num_rows is returning wrong values.
I'm sorry, I forgot to mention that this only happens when I try to look for words with special chars. Bebês, Câmeras, Calção are examples.
$sql = "
SELECT cattitle as category
FROM categories
WHERE cattitle = '$title'
";
$res = mysql_query($sql, $con) or die(mysql_error());
$num = mysql_num_rows($res);
I even have tried with mysql_result
$sql = "
SELECT count(cattitle) as category
FROM categories
WHERE cattitle = '$title'
";
$res = mysql_query($sql, $con) or die(mysql_error());
$num = mysql_result($res,0);
The worst thing is, when I run the query directly, I get the correct results ($num > 0).
I'm not that experienced programmer and, at first, I thought it was returning values from other queries, but I've checked and changed the name of those vars and the problem persisted.
Could be some kind of conflict? Can someone help me with this error?
Kind regards,
Your example is basic one, and it should work. It is even in PHP manual as example.
Try this way:
$sql = "
SELECT cattitle
FROM categories
WHERE cattitle = '$title'
LIMIT 1
";
$res = mysql_query($sql, $con) or die(mysql_error());
if ($row = mysql_fetch_assoc($res)) {
# category already exists, do smth?
}
I think your problem may be in wrong charsets for your mysql database and for string in your PHP script.
When you use mysql console then it convert symbols in correct charset.
Check charset and collate for your table and field cattitle.
Best solution will change it to UTF8
Also use UTF8 when write your script

Receive multiple columns from one sql request in PHP

I am working on a friend list function and I can't figure out how to correctly receive the values.
My code looks like this:
$getuid = $mysqli->prepare("SELECT `uid` FROM `users` WHERE name = ? OR name = ?");
$getuid->bind_param("ss", $user, $friend);
$getuid->execute();
$getuid->bind_result($uid);
$getuid->fetch();
$getuid->close();
$resetpass = $mysqli->prepare("INSERT INTO `friendlist` SET `friend1`=?, `friend2`=?, `accept`=0");
$resetpass->bind_param("ss", $uid[0], $uid[1]);
With the first query I get exactly two uid values back. I want to use them in the second query. It seems like bind_result is not working, neither as array nor when using two values in bind_result. How can I do this using mysqli. I can't use get_result because I'm on PHP 5.2 .
Anyone able to help me?
I think you need something like this. I have not tested it and there are probably even better ways to do this. I just tried the quickest change i could make to your original code to get it to work.
$query = "SELECT uid FROM users WHERE name = '".$user."' OR name = '".$friend."'";
$getuid = $mysqli->query($query);
if($uid = $getuid->fetch_assoc())
{
$query = "INSERT INTO friendlist SET friend1= '".$uid['uid'][0]."', friend2='".$uid['uid'][1]."', accept=0";
$mysqli->query($query)
}
$getuid->close();
Okay I finally understood the concept of fetch.
In order to receive all the values I have to retrieve them in a while-loop.
Here is the solution:
$getuid = $mysqli->prepare("SELECT `uid` FROM `users` WHERE name = ? OR name = ?");
$getuid->bind_param("ss", $user, $friend);
$arra = array();
$getuid->execute();
$getuid->bind_result($uid);
while ($getuid->fetch()) {
$arra[] = $uid;
}
Now I can call the array values using $arra[0] and $arra[1]

Categories